尝试获取上周一上午 12 点的日期时间 - 它总是给我中午 12 点

问题描述 投票:0回答:1

我正在尝试计算上周一中午 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。

这是调试器屏幕截图。 enter image description here

我做错了什么?这件事很直接。

java date groovy
1个回答
0
投票

以防万一有人对解决方案感兴趣。 我最终做了这样的事情:

LocalDateTime rangeEnd = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay()
LocalDateTime rangeStart = rangeEnd.minusWeeks(1)

[
       from: DateUtils.localDateTimeToDate(rangeStart),
       to: DateUtils.localDateTimeToDate(rangeEnd)
]

基本上,一行就可以回答原来的问题:)

© www.soinside.com 2019 - 2024. All rights reserved.