public static Date getStartOfTheDay() {
LocalDate currentDate = LocalDate.now();
// 将当前日期和零点时间合并
LocalDateTime currentDateTime = LocalDateTime.of(currentDate, LocalTime.MIDNIGHT);
// 获取0点的Date对象
return Date.from(currentDateTime.atZone(java.time.ZoneId.of("Asia/Shanghai")).toInstant());
}
public static Date getEndOfTheDay() {
LocalDate currentDate = LocalDate.now();
// 将当前日期和零点时间合并
LocalDateTime currentDateTime = LocalDateTime.of(currentDate, LocalTime.MAX);
// 获取0点的Date对象
return Date.from(currentDateTime.atZone(java.time.ZoneId.of("Asia/Shanghai")).toInstant());
}
上面是我的代码,我在零点多一点的时候,执行了以上的代码,并且写了一段这样的日志:
log.info("the start date is: {} and the end date is: {}", TimeUtils.getStartOfTheDay(), TimeUtils.getEndOfTheDay());
打出来的时间却是两天前的:
09/27 00:41:20 blood-sugar-dev-133 2024-09-26T16:41:19.814Z INFO 1 --- [blood-sugar-monitor] [nio-8080-exec-9] c.p.u.h.B.dao.impl.FoodDao : the start date is: Wed Sep 25 16:00:00 GMT 2024 and the end date is: Thu Sep 26 15:59:59 GMT 2024
如果是因为时区问题也可以理解,当前的GMT时间是26号,但是就算这样出来的时间也应该是26的0点-23:59吧?
LocalDateTime currentDateTime = LocalDateTime.of(currentDate, LocalTime.MAX);
以你这句代码为例,本质上你是先获取了当天最晚时间,如果当前是09-27号,utc+0时区,那么这句执行完currentDateTime已经是2024-09-27 23:59:59了,然后你再转成东八区Date.from(currentDateTime.atZone(java.time.ZoneId.of("Asia/Shanghai")).toInstant());,时间当然就错了