How to calculate number of days between two given dates
If you are looking for a utility method which computes the days between two given dates then you can use the following method
public static long daysBetweenDates(Date from, Date to) {
return TimeUnit.DAYS.convert((to.getTime() - from.getTime()), TimeUnit.MILLISECONDS);
}
Following is the complete Java program which uses the above method and prints days between given dates.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class DaysBetweenDates {
public static void main(String[] args) throws ParseException {
Date from = new SimpleDateFormat("yyyy-MM-dd").parse("2017-09-01");
Date to = new SimpleDateFormat("yyyy-MM-dd").parse("2017-10-01");
System.out.println("Difference between dates is: " + daysBetweenDates(from, to));
}
public static long daysBetweenDates(Date from, Date to) {
return TimeUnit.DAYS.convert((to.getTime() - from.getTime()), TimeUnit.MILLISECONDS);
}
}
Output:
Difference between dates is: 30