javadategroovy

Trying to get the datetime of 12am on last Monday - it always gives me 12pm


I am trying to calculate the Date object of the last Monday at 12 am. Here is my code:

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()

As you can see, I am setting the hour to 0. But, calendar.getTime() gives me 12:00:00.

Here is the debugger screenshot. enter image description here

What am I doing wrong? This thing is very strait-forward.


Solution

  • Just in case anyone is interested in the solution. I ended up doing something like this:

    LocalDateTime rangeEnd = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay()
    LocalDateTime rangeStart = rangeEnd.minusWeeks(1)
    
    [
           from: DateUtils.localDateTimeToDate(rangeStart),
           to: DateUtils.localDateTimeToDate(rangeEnd)
    ]
    

    Basically, a single line answers the original question :)