Calculate days between two Dates in Java 8
Asked Answered
I

14

376

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)
Intima answered 18/11, 2014 at 23:6 Comment(5)
Something like this for example?Lambskin
@Lambskin Not really - Duration is not the best fit to do that...Dive
@Dive Well, it's better than what the OP hadLambskin
@Dive Then what is?Lambskin
@Lambskin DAYS.between(localDate1, localDate2).Dive
C
626

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: Java SE 8 Date and Time.

Cerda answered 18/11, 2014 at 23:24 Comment(6)
That throws an exception, because the Duration.between method requires temporal objects capable of supporting the SECONDS unit. Instead, try Duration.between(today.atTime(0, 0), yesterday.atTime(0, 0)).toDays().Bog
Instead of today.atTime(0, 0) you can do today.atStartOfDay().Benzocaine
@REACHUS Maybe the -1 was a bit harsh because the code you propose works, but Duration is meant to measure "time-based amounts of time". There is a built-in way to measure a number of days which does not require converting from date to datetime.Dive
The better answer for LocalDate's is @Sunil B's answer below: ChronoUnit.DAYS.between(firstDate, secondDate)Arachne
@Lappro why is it better? It uses the same method as my answerCerda
@Cerda Ah right your first example is indeed the same, I didn't see that because the DAYS came from an import instead of ChronoUnit.DAYS. And glancing over details to find a quick solution isn't always the best strategy on my part ;)Arachne
A
197

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

ChronoUnit.DAYS.between(firstDate, secondDate)
Ammadis answered 18/11, 2014 at 23:29 Comment(1)
This solution should be the accepted answer since it is more concise.Pinochle
A
65

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.

Artemus answered 30/8, 2015 at 16:57 Comment(2)
The gotcha I just encountered with the first version of until is that it returns a Period object. That'll return a number of years/months/days between the two dates, not the actual number of days. And getDays() on the Period only returns the days part (not taking into account the number of years or months), rather than the total number of days. The second version works exactly as desired to get a number of days between two dates.Dispersoid
Is there's a complete alternative for this for this ? Since it needs Android SDk 26 and abovePurposely
R
23

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);
Repair answered 19/5, 2015 at 8:20 Comment(0)
T
19

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()));
Torr answered 20/2, 2019 at 16:13 Comment(0)
I
11

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);

    }

}
Incomputable answered 3/3, 2016 at 5:34 Comment(0)
G
11

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.

Gander answered 5/1, 2018 at 20:21 Comment(1)
FWIW... I'm not sure why both exist. Are there times that one is more readable and times that the other is? When/why?Gander
T
7

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)));
Taxexempt answered 5/10, 2017 at 22:51 Comment(0)
K
6

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);
    }
}
Koslo answered 15/8, 2016 at 17:13 Comment(0)
E
4

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()));
        }
Eddi answered 2/10, 2018 at 14:16 Comment(0)
S
4

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();
}
Secondly answered 30/11, 2018 at 6:37 Comment(1)
In fall in the trap to use ' Period.between(date1, date2).getDays()' without realizing that you loose the months and years of the difference.Casilde
H
4

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());
}
Hypnotic answered 3/6, 2019 at 9:24 Comment(0)
R
3

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

Robot answered 1/10, 2019 at 12:9 Comment(0)
A
1
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);
Atmosphere answered 1/8, 2020 at 5:40 Comment(2)
java.time.temporal.ChronoUnit java 8 implemancationAtmosphere
Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.Sundstrom

© 2022 - 2024 — McMap. All rights reserved.