简体   繁体   中英

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);

In UTC:

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

or

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

since calendar starts at 01.01.1970, 01:00 . you have to make further modifications to the code.using below approach avoids that so this will performs faster.

dateInput.toInstant().atZone(ZoneId.systemDefault()).getHour();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM