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:

Newsletter – Week 7, 2017