Java Calendar set the time to 12 o'clock the previous day in UTC

Can someone explain why or is this code incorrect?

// main Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); System.out.println(calendar.getTime()); calendar.add(Calendar.DATE, -1); System.out.println(calendar.getTime()); calendar.set(Calendar.HOUR_OF_DAY, 0); System.out.println(calendar.getTime()); 

He produces:

 Fri Jan 28 15:27:35 EST 2011 Thu Jan 27 15:27:35 EST 2011 Wed Jan 26 19:27:35 EST 2011 

Am I missing something obvious? I expect to see something like Thu Jan 27 00:27:35 EST 2011

Thanks.

+4
source share
3 answers

You print it in the default time zone, not in UTC. Although your calendar knows the time zone that interests you, the java.util.Date returned by getTime() is not ... and Date.toString() uses the system time zone.

Given that you indicated in the subject line that you wanted 12 AM at UTC, why do you expect to see Thu Jan 27 00:27:35 EST 2011? EST does not match UTC.

EDIT: As always, I just wanted to point out that Joda Time is usually a much more convenient API for using date / time arithmetic in Java. You are currently getting the correct answer, but I still recommend moving to Joda :)

+3
source

EST - UTC - 5 hours, so 19:27 EST corresponds to 00:27 UTC. It seems logical to me. Use the date format with the UTC locale to display your calendars, instead of using your default locale.

+2
source

For UTC calculations (only), you may find that using long is easier.

 long time = System.currentTimeMillis(); // yesterday at 12:00:00.000 am. long yesterday = (time / 86400000 - 1) * 86400000; 
0
source

Source: https://habr.com/ru/post/1337533/


All Articles