Calculate the number of days between two dates

The issues with date and time processing in old versions of Java led many developers to use tricky workarounds or third-party libraries like Joda-Time for that.

Oracle in collaboration with Stephen Colebourne introduced the implementation of JSR 310: Date and Time API in Java SE 1.8.  The new date and time API with dramatically improved safety and functionality.  Nevertheless,  developers still use old approaches for date and time processing even using Java 1.8 for development ignoring all improvements provided there out of the box.

This is one of the many real cases when you have two dates and should calculate the number of days between these dates. The small examples below illustrate how it can be solved in case of using new API provided by Java1.8

Firstly, how it might be implemented using Java 1.7:

and the same implementation using Java 1.8:

For dates with time it can be solved in a similar manner using new API:

If you want to know more about new date and time processing API – here the links to the official documentation:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.