Calculate days between two Dates in Java 8

JavaJava 8Java TimeDaysDate Difference

Java Problem Overview


I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.

The function needs to be compliant with these restrictions:

  1. Prevent errors from date savetime
  2. Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)

Java Solutions


Solution 1 - Java

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document.

Solution 2 - Java

Based on VGR's comments here is what you can use:

ChronoUnit.DAYS.between(firstDate, secondDate)

Solution 3 - Java

You can use until:

LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);

System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));

Output:

Until christmas: P5M21D
Until christmas (with crono): 174

As mentioned in a comment, if no unit is specified until returns Period.

Snippet from the documentation:

>A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
>This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.

Solution 4 - Java

DAYS.between

You can use DAYS.between from java.time.temporal.ChronoUnit

e.g.

import java.time.temporal.ChronoUnit;
...

long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
    return DAYS.between(dateBefore, dateAfter);

Solution 5 - Java

> If startDate and endDate are instance of java.util.Date

We can use the between( ) method from ChronoUnit enum:

public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
    //..
}

ChronoUnit.DAYS count days which completed 24 hours.

import java.time.temporal.ChronoUnit;

ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());

//OR 

ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));

Solution 6 - Java

Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).

The docs for both actually mention both approaches and say to use whichever one is more readable.

Solution 7 - Java

Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :

Output : *Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368. *Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368

package com.bitiknow.date;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

/**
 * 
 * @author pradeep
 *
 */
public class LocalDateTimeTry {
	public static void main(String[] args) {

		// Date in String format.
		String dateString = "2015-03-01";

		// Converting date to Java8 Local date
		LocalDate startDate = LocalDate.parse(dateString);
		LocalDate endtDate = LocalDate.now();
		// Range = End date - Start date
		Long range = ChronoUnit.DAYS.between(startDate, endtDate);
		System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
				+ " is  ==> " + range);

		range = ChronoUnit.DAYS.between(endtDate, startDate);
		System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
				+ " is  ==> " + range);

	}

}

Solution 8 - Java

Get number of days before Christmas from current day , try this

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));

Solution 9 - Java

Here you go:

public class DemoDate {
	public static void main(String[] args) {
		LocalDate today = LocalDate.now();
		System.out.println("Current date: " + today);

		//add 1 month to the current date
		LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
		System.out.println("Next month: " + date2);

		// Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
		long daysNegative = ChronoUnit.DAYS.between(date2, today);
		System.out.println("Days : "+daysNegative);
		
		// Put old date 1st and new date 2nd in 'between' method to get +ve date difference
		long datePositive = ChronoUnit.DAYS.between(today, date2);
		System.out.println("Days : "+datePositive);
	}
}

Solution 10 - Java

If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -

public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
  // Check for null values here

  return endDate.toEpochDay() - startDate.toEpochDay();
}

Solution 11 - Java

> get days between two dates date is instance of java.util.Date

public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
    		return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
    	}

Solution 12 - Java

I know this question is for Java 8, but with Java 9 you could use:

public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
    return startDate.datesUntil(endDate)
      .collect(Collectors.toList());
}

Solution 13 - Java

Use the class or method that best meets your needs:

  • the Duration class,
  • Period class,
  • or the ChronoUnit.between method.

A Duration measures an amount of time using time-based values (seconds, nanoseconds).

A Period uses date-based values (years, months, days).

The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.

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

Solution 14 - Java

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

LocalDate dateBefore =  LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
	
long daysBetween =  ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
	
System.out.println(daysBetween);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcosView Question on Stackoverflow
Solution 1 - JavasyntagmaView Answer on Stackoverflow
Solution 2 - JavaSunil BView Answer on Stackoverflow
Solution 3 - Javacatch23View Answer on Stackoverflow
Solution 4 - JavaPiotr FrygaView Answer on Stackoverflow
Solution 5 - JavaPawanView Answer on Stackoverflow
Solution 6 - JavanafgView Answer on Stackoverflow
Solution 7 - JavaPradeep PadmarajaiahView Answer on Stackoverflow
Solution 8 - Javasurvivor_27View Answer on Stackoverflow
Solution 9 - JavaPAAView Answer on Stackoverflow
Solution 10 - JavalevenshteinView Answer on Stackoverflow
Solution 11 - JavaMohamed.AbdoView Answer on Stackoverflow
Solution 12 - JavaXxtreemView Answer on Stackoverflow
Solution 13 - JavaSamuelView Answer on Stackoverflow
Solution 14 - JavaMalleswar ReddyView Answer on Stackoverflow