我正在尝试计算上周一中午 12 点的 Date 对象。 这是我的代码:
Calendar calendar = Calendar.getInstance()
calendar.setTime(currentDate)
Integer dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
if (dayOfWeek > Calendar.MONDAY) {
Integer daysDifferenceFromMonday = dayOfWeek - Calendar.MONDAY
calendar.add(Calendar.DATE, -daysDifferenceFromMonday)
} else if (dayOfWeek < Calendar.MONDAY) {
// it means that we are on Sunday and we need last sunday
Integer daysDifferenceFromMonday = 7 - (Calendar.MONDAY - dayOfWeek)
calendar.add(Calendar.DATE, -daysDifferenceFromMonday)
}
calendar.set(Calendar.MILLISECOND, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.HOUR, 0)
Date toDate = calendar.getTime()
如您所见,我将小时设置为 0。但是,
calendar.getTime()
给了我 12:00:00。
我做错了什么?这件事很直接。
以防万一有人对解决方案感兴趣。 我最终做了这样的事情:
LocalDateTime rangeEnd = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay()
LocalDateTime rangeStart = rangeEnd.minusWeeks(1)
[
from: DateUtils.localDateTimeToDate(rangeStart),
to: DateUtils.localDateTimeToDate(rangeEnd)
]
基本上,一行就可以回答原来的问题:)