java-8java-timejava.util.calendar

Calculate calender days between two dates in java


is there any way to calculate calendar days between two dates. I tried with below code but looks like it gives 1 day as answer. But I am expecting the difference between this date is 2 days. No need to consider the hours/minutes/seconds. For e.g in the below code 01-06-2023 is one day and 02-06-2023 is another day so the difference should be 2 days.

        LocalDateTime startLdt = LocalDateTime.parse("2023-06-01T00:00");
        LocalDateTime endLdt   = LocalDateTime.parse("2023-06-02T23:59");
        
        LocalDate startdt = LocalDate.parse("2023-06-01");
        LocalDate enddt   = LocalDate.parse("2023-06-02");

        long diffInDays = ChronoUnit.DAYS.between(startLdt, endLdt);        
        long noOfDaysBetween = ChronoUnit.DAYS.between(startdt, enddt);

        System.out.println(diffInDays);  //1
        System.out.println(noOfDaysBetween);  //1

correct me in case if there is any issues in my understanding of Calender days.


Solution

  • You should just add 1 to the result that ChronoUnit.DAYS.between gives you.

    If you are working with LocalDateTimes, you should convert them to LocalDates first, since you only care about the date part.

    LocalDateTime startLdt = LocalDateTime.parse("2023-06-01T05:00");
    LocalDateTime endLdt   = LocalDateTime.parse("2023-06-02T00:00");
    
    LocalDate startdt = LocalDate.parse("2023-06-01");
    LocalDate enddt   = LocalDate.parse("2023-06-02");
    
    long localDateTimeResult = ChronoUnit.DAYS.between(startLdt.toLocalDate(), endLdt.toLocalDate()) + 1;
    long localDateResult = ChronoUnit.DAYS.between(startdt, enddt) + 1;
    
    System.out.println(localDateTimeResult); // 2
    System.out.println(localDateResult); // 2