定义一个日期处理类,要求能实现如下功能: 显示当前系统日期和时间 给定一个日期值,计算并显示若干天后的日期值 计算并显示两个日期之间相距的天数
时间: 2024-02-22 10:59:42 浏览: 18
以下一个简单的日期处理类,满足题目要求:
```java
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
// 显示当前系统日期和时间
public static void showCurrentDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println(dateTime);
}
// 计算并显示若干天后的日期值
public static void showDateAfterDays(String currentDate, int days) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = dateFormat.parse(currentDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, days);
Date newDate = calendar.getTime();
String newDateString = dateFormat.format(newDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
// 计算并显示两个日期之间相距的天数
public static void showDaysBetweenDates(String date1, String date2) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date startDate = dateFormat.parse(date1);
Date endDate = dateFormat.parse(date2);
long diff = endDate.getTime() - startDate.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
使用示例:
```java
public static void main(String[] args) {
// 显示当前系统日期和时间
DateUtils.showCurrentDateTime();
// 计算并显示若干天后的日期值
DateUtils.showDateAfterDays("2021-01-01", 10);
// 计算并显示两个日期之间相距的天数
DateUtils.showDaysBetweenDates("2021-01-01", "2021-01-11");
}
```
输出结果:
```
2021-05-01 15:23:45
2021-01-11
10
```