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
The Split() Method in Java Does Not Work on a Dot (.)
Compile and Execute a Jdk Preview Feature with Maven
How to Copy Java Collections List
How to Get Whole and Fractional Parts from Double in Jsp/Java
How to Disable Javac's Inlining of Static Final Variables
Keylistener, Keypressed Versus Keytyped
Performance Difference Between a Wild Card Import and the Required Class Import
What Java 8 Stream.Collect Equivalents Are Available in the Standard Kotlin Library
Why Isn't This Code Causing a Concurrentmodificationexception
Hash String via Sha-256 in Java
Maven Jacoco: Not Generating Code Coverage Report
How to Calculate the Difference Between Two Arraylists
Springboot - Making Jar Files - No Auto Configuration Classes Found in Meta-Inf/Spring.Factories
When to Use Atomicreference in Java