Getting the latest time for the current day via Calendar gives the wrong result

I am trying to get the last time of the current day.
For example:
The last time for today will be 07/10/2015 23: 59: 59: 999

So I wrote 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 that should give me the last millisecond of that day. But when I use this method for example:

Date date = getLastDateOfDay();

      

Then the date is: 11.07.2015 23: 59: 59: 999

Am I missing something? Did I do something wrong? Please help me with this.
thanks in advance.

+3


source to share


4 answers


You cannot use Hour from 23

see the Javadoc from Calendar



public static final int HOUR

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

+3


source


set



cal.set(Calendar.HOUR_OF_DAY, 23);

      

+1


source


You can try setting an explicit timezone for your calendar instance, i.e.

final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC");

      

This answer might also help: What is the default timezone for java.util.Calendar.?

0


source


Hopefully this might be what you are looking for.

private static Date getLastDateOfDay() {
        final Calendar cal = Calendar.getInstance();

        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTime();
    }

      

0


source







All Articles