Java 8 – How to calculate days between two dates?

In Java 8, we can use ChronoUnit.DAYS.between(from, to) to calculate days between two dates.

1. LocalDate

JavaBetweenDays1.java

package com.mkyong.java8;

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

public class JavaBetweenDays1 {

    public static void main(String[] args) {

        LocalDate from = LocalDate.now();
        LocalDate to = from.plusDays(10);

        long result = ChronoUnit.DAYS.between(from, to);
        System.out.println(result);    // 10

    }

}

Output


10

2. LocalDateTime

JavaBetweenDays2.java

package com.mkyong.java8;

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

public class JavaBetweenDays2 {

    public static void main(String[] args) {

        LocalDateTime from = LocalDateTime.now();
        LocalDateTime to = from.plusDays(10);

        long result = ChronoUnit.DAYS.between(from, to);
        System.out.println(result);     // 10

        LocalDateTime to2 = from.minusDays(10);
        long result2 = ChronoUnit.DAYS.between(from, to2);
        System.out.println(result2);    // -10

    }

}

Output


10
-10

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar