Fastest way to get java.util.date hour?

When you start with the java.util.date object: what is the best way to get the hour part as an integer regarding performance?

I need to repeat several million dates, so performance matters.

Usually I get an 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); 
+5
source share
2 answers

In UTC:

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

or

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

since the calendar starts on 01.01.1970, 01:00 . You must make additional changes to the code. Using the approach below avoids this, so it will be faster.

 dateInput.toInstant().atZone(ZoneId.systemDefault()).getHour(); 
+3
source

All Articles