3

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.

Naxos84
  • 1,890
  • 1
  • 22
  • 34
  • 1
    How *exactly* are you seeing "11.07.2015 23:59:59:999"? That's not the result of `Date.toString()`, for example. Also note that currently you're using the system time zone - are you sure that's what you want? – Jon Skeet Jul 10 '15 at 11:10
  • When I do this I get the current date and 23:59:59 (in my local timezone) - we need to know how you're calling it. – arcy Jul 10 '15 at 11:14
  • `Calendar` is a bit hard to use. See http://stackoverflow.com/questions/31219411/does-the-setmonth-method-of-java-calendar-work-wrong, and http://stackoverflow.com/questions/6722542/java-calendar-date-is-unpredictable-after-setting-day-of-week. – serv-inc Jul 10 '15 at 11:17

3 Answers3

3

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.

Community
  • 1
  • 1
user140547
  • 7,750
  • 3
  • 28
  • 80
  • Thank you very much for pointing this out. Marked this answer as correct cause it was the most precise one with good explanation. – Naxos84 Jul 10 '15 at 11:19
1

set

cal.set(Calendar.HOUR_OF_DAY, 23);
vels4j
  • 11,208
  • 5
  • 38
  • 63
0

You could try set explicit timezone for your Calendar instance, i.e:

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

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

Community
  • 1
  • 1
plain_text
  • 91
  • 5