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 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 to share
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 to share