javadatecalendar

Getting the last time for the current day via the Calendar gives a wrong result


I'm trying to get the last time of the current day.
For example:
The last time for today would be 10.07.2015 23:59:59:999

Therefore i have written the following method:

private static Date getLastDateOfDay() {
    final Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MILLISECOND, 999);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.HOUR, 23);
    return cal.getTime();
}

This should get the current date and then set:
hours to 23
minutes to 59
seconds to 59
miliseconds to 999

so this should give me the very last milisecond of this day. But when i use this method like:

Date date = getLastDateOfDay();

Then the date has the value of: 11.07.2015 23:59:59:999

Am i missing something? Did i make something wrong? Please help me with this.
Thx in advance.


Solution

  • You can't use Hour with 23

    see Javadoc from Calendar

    public static final int HOUR

    Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.