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

1. LocalDate

JavaBetweenDays1.java

package com.favtuts.time;

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

public class CalculateDaysBetweenDates {
    
    public static void main(String[] args) {
        calculateDaysBetweenLocalDate();
    }

    static void calculateDaysBetweenLocalDate() {
        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.favtuts.time;

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

public class CalculateDaysBetweenDates {
    
    public static void main(String[] args) {
        calculateDaysBetweenLocalDateTime();
    }

    static void calculateDaysBetweenLocalDateTime() {
        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

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-basic/time

References

Leave a Reply

Your email address will not be published. Required fields are marked *