How to calculate the difference in days in yyyy-MM-dd format

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

public class Main {
    public static void main(String[] args) {
        String dateString1 = "2023-01-01";
        String dateString2 = "2023-07-29";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.parse(dateString1, formatter);
        LocalDate date2 = LocalDate.parse(dateString2, formatter);

        long daysDiff = ChronoUnit.DAYS.between(date1, date2);

        System.out.println("天数差异:" + daysDiff);
    }
}

=========================================================================

=========================================================================

To calculate the difference in days between two dates in "yyyy-MM-dd" format, you can follow these steps:

  1. Parses a string date into LocalDatean object.

  2. You can use the method java.time.format.DateTimeFormatterin the class ofPattern()to create a date format pattern, and then use parse()the method to parse the string into LocalDatean object.

  3. Parses a string date into LocalDatean object. You can use the method java.time.format.DateTimeFormatterin the class ofPattern()to create a date format pattern, and then use parse()the method to parse the string into LocalDatean object.

 

Guess you like

Origin blog.csdn.net/monicateacat/article/details/131992246