Categories
Java

days between two dates with Java 8

A common task in programming is to calculate a difference between two dates / timestamps. Java 8 introduced a new Date/Time API for solving such problems in an easy way.

To use this API you have to use LocalDate or LocalTime. So if you have an “old school” java.util.Date instance, you must convert it..

LocalDate localDate = new Date().toInstant().atZone(ZoneId.systemDefault());

Now you can calculate the difference between two values:

//now
LocalDate localDate1 = LocalDate.now();
//a converted future date 
LocalDate localDate2 = dateInFuture.toInstant().atZone(ZoneId.systemDefault());
int differenceInDays = localDate1.until(localDate2, ChronoUnit.DAYS)

A second variant is to use ChronoUnit method between:

//now
LocalDate localDate1 = LocalDate.now();
//a converted future date 
LocalDate localDate2 = dateInFuture.toInstant().atZone(ZoneId.systemDefault());
int differenceInDays = ChronoUnit.DAYS.between(localDate1, localDate2)