Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Jun 30, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Calculating # of days between two dates

I need help to calculate the number of days between two dates. This may seem like a trivial question, but for the life of me, I cannot find a way for the Calendar or Date class to achieve this.

This is actually not a trivial question. The Java time classes are ill-suited for performing calendar arithmetic. They seem to have been designed with time storage in mind rather than time manipulation.

One way to achive what you desire is to call getTime() in the Date class to obtain a representation of the two dates in seconds since January 1, 1970. You would then subtract the smaller value from the larger and convert the resulting number of seconds into days (there are 86,400 seconds in a day). However, you will run into some limitations with the range of dates that can be represented in this manner. You may have to roll your own code or look for a third-party solution.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date