java计算两个string类型日期的天数差
时间: 2023-08-04 07:14:05 浏览: 128
可以使用Java中的日期时间类`LocalDate`来计算两个字符串类型日期的天数差。
示例代码如下:
```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateUtils {
public static long daysBetween(String start, String end) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(start, formatter);
LocalDate endDate = LocalDate.parse(end, formatter);
return ChronoUnit.DAYS.between(startDate, endDate);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
String start = "2021-01-01";
String end = "2021-02-01";
long days = DateUtils.daysBetween(start, end);
System.out.println("Days between " + start + " and " + end + ": " + days);
}
}
```
输出结果为:
```
Days between 2021-01-01 and 2021-02-01: 31
```
阅读全文