需求
休息日例子
自定义日期类MyDate
- 日期
- 记录是否是休息日
- 记录是否是周末
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MyDate {
// 日期
LocalDate date;
// 是否休息
boolean isRest;
// 是否是周末
boolean isWeekend;
}
starter启动器
// 1. 定义起始的休息时间 2022-02-03
LocalDate startDate = LocalDate.of(2022, 2, 3);
// 2.输入年月 获取当月所有的日期 类型是LocalDate
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份:");
int month = scanner.nextInt();
// 3. 获取当月的所有日期
LocalDate monthStartDate = LocalDate.of(year, month, 1);
int days = monthStartDate.lengthOfMonth();
// 定义一个MyDate的List,存储计算之后的结果
List<MyDate> myDateList = new ArrayList<>();
for (int i = 0; i < days; i++) {
LocalDate currentDate = monthStartDate.plusDays(i);
// 使用当前日期减去起始日期,获取相差的天数,如果相差是3的倍数,就是休息日
int diff = (int) (currentDate.toEpochDay() - startDate.toEpochDay());
boolean isRest = diff % 3 == 0;
// 判断是否是周末
boolean isWeekend = currentDate.getDayOfWeek().getValue() >= 6;
MyDate myDate = new MyDate(currentDate, isRest, isWeekend);
myDateList.add(myDate);
}
myDateList.forEach(myDate -> {
String dateStr = myDate.getDate().toString();
if (myDate.isWeekend) {
dateStr = dateStr + "【周末】";
}
if (myDate.isRest) {
dateStr = dateStr + "【休息】";
}
// 规定字符串长度为20 不足的补空格
dateStr = String.format("%-20s", dateStr);
System.out.print(dateStr);
if (myDate.isRest) {
System.out.println();
}
});
高考倒计时
关键代码: Duration duration = Duration.between(now, startDate);
- 使用Duration 计算两个 LocalDateTime 的时间间隔
//1. 定义高考时间 2024-06-07
LocalDateTime startDate = LocalDateTime.of(2024, 6, 7, 9, 0, 0);
//2. 设置1秒的时间间隔的计时器
while (true) {
//3. 获取当前时间
LocalDateTime now = LocalDateTime.now();
//4. 计算当前时间距离高考时间的毫秒数
Duration duration = Duration.between(now, startDate);
long days = duration.toDays();
long hours = duration.toHours() % 24;
long minutes = duration.toMinutes() % 60;
long seconds = duration.getSeconds() % 60;
//5. 输出当前时间距离高考时间的天 时 分 秒
System.out.println("距离高考还有:" + days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒");
//6. 休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}