Calculate Days Between Two Dates in Java
There are several ways to calculate days between two dates in Java. Some are as follows:
In Java 8:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class CalculateDays {
public static void main(String[] args) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd MM yyyy");
String fromDate = "12 01 2021";
String toDate = "28 01 2021";
LocalDate fromLocalDate = LocalDate.parse(fromDate, dateFormatter);
LocalDate toLocalDate = LocalDate.parse(toDate, dateFormatter);
long days = ChronoUnit.DAYS.between(fromLocalDate, toLocalDate) + 1;
System.out.println("Days " + days);
}
}
The above code will give the following output:
Days 17
Prior to Java 8:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class CalculateDays {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
String fromDate = "12 01 2021";
String toDate = "28 01 2021";
dateFormat.setTimeZone(TimeZone.getTimeZone("America/"));
long days = 0;
try {
Date dateFrom = dateFormat.parse(fromDate);
Date dateTo = dateFormat.parse(toDate);
days = dateTo.getTime() - dateFrom.getTime();
days = TimeUnit.DAYS.convert(days, TimeUnit.MILLISECONDS) + 1;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Days " + days);
}
}
The above code will give the following output:
Days 17