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:
-
Parses a string date into
LocalDate
an object. -
You can use the method
java.time.format.DateTimeFormatter
in the classofPattern()
to create a date format pattern, and then useparse()
the method to parse the string intoLocalDate
an object. -
Parses a string date into
LocalDate
an object. You can use the methodjava.time.format.DateTimeFormatter
in the classofPattern()
to create a date format pattern, and then useparse()
the method to parse the string intoLocalDate
an object.