Newsletter – Week 23, 2017

News:

Articles:

Videos:

Newsletter – Week 22, 2017

News:

Articles:

Videos:

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:


//input dates
final String start = "2010-01-15";
final String end = "2011-03-18";
// parse the dates
final SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
final Date startDate = dateFormat.parse( start );
final Date endDate = dateFormat.parse( end );
// calculate the number of days between start and end dates
long daysDuration = Math.round( ( endDate.getTime() – startDate.getTime() ) / (double) ( 1000 * 60 * 60 * 24 ) );

view raw

dates1.7.java

hosted with ❤ by GitHub

and the same implementation using Java 1.8:


// input dates
final String start = "2010-01-15";
final String end = "2011-03-18";
// parse the dates
final LocalDate startDate = LocalDate.parse( start );
final LocalDate endDate = LocalDate.parse( end );
// calculate the number of days between start and end dates
long daysDuration = ChronoUnit.DAYS.between( startDate , endDate );

view raw

dates1.8.java

hosted with ❤ by GitHub

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


// input dates
final String start = "2010-01-15T00:00:00";
final String end = "2011-03-18T18:00:00";
// parse the dates
final LocalDateTime startDate = LocalDateTime.parse(start);
final LocalDateTime endDate = LocalDateTime.parse(end);
// calculate the number of days between start and end dates
long daysDuration = Duration.between(startDate, endDate).toDays();

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

http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html

https://docs.oracle.com/javase/tutorial/datetime/iso/index.html