The Answer by Mehta is correct.
Use java.time
Also, you are entirely using the wrong classes.
The troublesome old date-time classes (Date
, Calendar
, etc.) are now legacy, supplanted by the java.time classes.
Instant
Instead of java.util.Date
use Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
If you need to interface with old code not yet updated to java.time, convert. Look to new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant();
Generally best to work in UTC, especially for data storage and data exchange. So make frequent use of the Instant
class.
Time zone
For determining days, we need to determine dates. And for determining dates, we need time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight Paris France is a new day while still being “yesterday” in Montréal Québec.
ZonedDateTime
Apply a time zone (ZoneId
) to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone();
ChronoUnit
Do not try to do the date-time math yourself. To begin with, you are assuming every hour is sixty minutes, every day is 24 hours, and so on. You would be wrong. Anomalies such as Daylight Saving Time (DST) and politicians frequently re-defining time zones mean such assumptions are wrong. Let java.time do the math.
You seem to want a number of days between two points in time. For that, use the ChronoUnit
enum, an implementation of TemporalUnit
. When fed ZonedDateTime
objects, the ChronoUnit
class is savvy with time zones and anomalies such as DST change-over. Be sure to read the class doc to know and understand its behavior in such situations.
long days = ChronoUnit.DAYS.between( zdtStart , zdtStop );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.