Java Calendar not giving end of hour

Tags: ,



Based on Epoch seconds, I convert it to the start of hour and end of hour.

    long epochSeconds = 1589374800L;
    Instant instant = Instant.ofEpochSecond(epochSeconds);
    Calendar now = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("Asia/Kolkata")));
    now.setTimeInMillis(instant.toEpochMilli());

    System.out.println(now.getTime()); // Correct --> Wed May 13 06:00:00 PDT 2020

    Calendar endOfHour = (Calendar)now.clone();
    endOfHour.set(Calendar.MINUTE, 59);
    endOfHour.set(Calendar.SECOND, 59);
    endOfHour.set(Calendar.MILLISECOND, 999);

    System.out.println(endOfHour.getTime()); // Wrong ---> Wed May 13 06:29:59 PDT 2020

The start of hour seems correct, but the end of hour is not giving it right, instead of upto 59 minute, 59 second, 999 millisecond it is giving only half hour difference.

Answer

You are mixing java.time and java.util.Calendar types. Don’t do that. For one thing, you’re losing the TimeZone you specified when you clone. Basically, Calendar is a mess. But you don’t need it here, something like

long epochSeconds = 1589374800L;
LocalDateTime date = Instant.ofEpochSecond(epochSeconds) //
        .atZone(ZoneId.of("Asia/Kolkata")) //
        .toLocalDateTime();
System.out.println(date);
LocalDateTime endOfHour = date.withMinute(59) //
        .withSecond(59) //
        .with(ChronoField.MILLI_OF_SECOND, 999);
System.out.println(endOfHour);

Should meet your needs. Here that outputs

2020-05-13T18:30
2020-05-13T18:59:59.999


Source: stackoverflow