From a java.util.Date( a timestamp), how can I get the hour of day?
In joda.time I use getHourOfDay().
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);