Compute days between 2 datesTag(s): Date and Time
Java 8
Using java.time.LocalDate and java.time.temporal.ChronoUnitimport java.time.LocalDate; import java.time.temporal.ChronoUnit; public class DateTest { public static void main(String[] args) { LocalDate pastDate = LocalDate.of(2017, 7, 20); LocalDate nowDate = LocalDate.now(); long days = ChronoUnit.DAYS.between(pastDate, nowDate); System.out.printf("%s %s days between : " + days, pastDate, nowDate); } }
Java 7 or less
One technique is to compute by hand the number of milliseconds between two dates and then convert the result in days.import java.util.*; public class DateUtils { private DateUtils() { } static final long ONE_HOUR = 60 * 60 * 1000L; public static long daysBetween(Date d1, Date d2){ return ( (d2.getTime() - d1.getTime() + ONE_HOUR) / (ONE_HOUR * 24)); } /* testing */ public static void main(String[] args) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); Calendar first = Calendar.getInstance(); first.set(2008, Calendar.AUGUST, 1); Calendar second = Calendar.getInstance(); System.out.println (DateUtils.daysBetween(first.getTime(),second.getTime()) + " day(s) between " + sdf.format(first.getTime()) + " and " + sdf.format(second.getTime())); /* * output : * 21 day(s) between 20080801 and 20080822 */ } }
Another way would be to compute the julian day number of both dates and then do the substraction. See this HowTo. Thanks to P. Hill for the tip.
The package java.util.concurrent.TimeUnit; provides a class to make conversion between milliseconds and days easier.
import java.util.*; import java.util.concurrent.TimeUnit; public class DateUtils { private DateUtils() { } public static long getDifference(Calendar a, Calendar b, TimeUnit units) { return units.convert (b.getTimeInMillis() - a.getTimeInMillis(), TimeUnit.MILLISECONDS); } /* testing */ public static void main(String[] args) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd"); Calendar augustfirst2008 = Calendar.getInstance(); augustfirst2008.set(2008, Calendar.AUGUST, 1); // 2008-08-01 Calendar today = Calendar.getInstance(); // today System.out.println (DateUtils.getDifference(augustfirst2008,today,TimeUnit.DAYS) + " day(s) between " + sdf.format(augustfirst2008.getTime()) + " and " + sdf.format(today.getTime())); } /* * output : * 921 day(s) between 20080801 and 20110208 (example) */ }
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com