devxlogo

Calculating # of days between two dates

Calculating # of days between two dates

Question:
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 away for the Calendar or Date class to achieve this.

Answer:
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 thantime manipulation.

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

See also  How College Students Can Shape the Future of Tech Responsibility
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist