0

From a java.util.Date( a timestamp), how can I get the hour of day?

In joda.time I use getHourOfDay().

Mouna
  • 2,691
  • 2
  • 21
  • 33

1 Answers1

3

There are multiple solutions for this. If you wish to use the Java 8 classes from java.time the following you need to covert a Date to one of the DateTime classes. The following can be used to convert a Date to a ZonedDateTime where you then can get the hour:

Date date = new Date();

// Convert to java 8 ZonedDateTime
Date date = new Date();
final ZonedDateTime dateTime = date.toInstant()
        .atZone(ZoneId.systemDefault());

// Get the hour
int hour = dateTime.getHour();

Quite verbose as you have noticed but the simple reason for this is that a Date is sort of an Instant

Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

Another approach is simply to get the field from a Calendar instance.

final Calendar instance = Calendar.getInstance();
instance.setTime(date);
final int hourOfDay = instance.get(Calendar.HOUR_OF_DAY);
Community
  • 1
  • 1
wassgren
  • 16,439
  • 5
  • 53
  • 71
  • 1
    You convert `ZonedDateTime` to `LocalDateTime`, but `getHour()` is also available on `ZonedDateTime`, so the extra conversion is unnecessary. – bowmore Jan 19 '15 at 14:37