Java: Getminutes and Gethours

Getting hours,minutes, and seconds from Date?

Use Calendar:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);

From Date javadoc:

Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).

Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.

Get hour from date() in java

Mathematical manipulation of date/times values is ignorant and possibly the worst thing you can do. There are a lot of rules which surround date/time manipulation, which is best left to a decent and well tested API.

Since Java 8, you should be using the java.time API or it's backport for earlier versions.

For example...

Instant now = Instant.now();
Instant then = now.minus(2, ChronoUnit.DAYS);

System.out.println(Duration.between(then, now).toHours());

which prints 48

What should I use instead of the deprecated Date.getHours()

You should be using a Calendar or the Joda Time library.

However if you can only use Date, this is your only method. Note, this will not adjust for timezone.



Related Topics



Leave a reply



Submit