membersound membersound - 5 months ago 13
Java Question

Fastest way to get hour of java.util.date?

When starting from a

java.util.date
object: what is the best way getting the hour part as an
integer
regarding performance?

I have to iterate a few million dates, thus performance matters.

Normally I'd get the hour as follows, but maybe there are better ways?

java.util.Date date;
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);

Answer

In UTC:

int hour = (int)(date.getTime() % 86400000) / 3600000;

or

 long hour = (date.getTime() % 86400000) / 3600000;