Java中string类型的日期计算差值
时间: 2023-09-13 14:05:26 浏览: 99
在 Java 中,可以使用 SimpleDateFormat 类来将字符串转换成日期对象,然后再使用 Calendar 类来进行日期计算。以下是一个示例代码,计算两个日期之间的天数差值:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static long getDaysBetween(String startDateStr, String endDateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date startDate = sdf.parse(startDateStr);
Date endDate = sdf.parse(endDateStr);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long daysBetween = (endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis()) / (1000 * 60 * 60 * 24);
return daysBetween;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
public static void main(String[] args) {
String startDateStr = "2021-01-01";
String endDateStr = "2021-01-05";
long daysBetween = getDaysBetween(startDateStr, endDateStr);
System.out.println("Days between " + startDateStr + " and " + endDateStr + ": " + daysBetween);
}
}
```
输出结果为:
```
Days between 2021-01-01 and 2021-01-05: 4
```
注意:日期格式字符串必须与实际输入的日期字符串格式相同,否则会抛出 ParseException 异常。
阅读全文