Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java.util.Date: try to understand UTC and ET more

I live in North Carolina, btw, which is on the East Side. So I compile and run this code and it print out the same thing. The documentation say that java.util.date try to reflect UTC time.

Date utcTime = new Date();
Date estTime = new Date(utcTime.getTime() + TimeZone.getTimeZone("ET").getRawOffset());
DateFormat format = new SimpleDateFormat("dd/MM/yy h:mm a");
System.out.println("UTC: " + format.format(utcTime));
System.out.println("ET: " + format.format(estTime));   

And this is what I get

UTC: 11/05/11 11:14 AM
ET: 11/05/11 11:14 AM

But if I go to this website which try to reflect all different time, UTC and ET are different. What did I do wrong here

like image 784
Thang Pham Avatar asked May 11 '11 15:05

Thang Pham


2 Answers

That's because getRawOffset() is returning 0 - it does that for me for "ET" as well, and in fact TimeZone.getTimeZone("ET") basically returns GMT. I suspect that's not what you meant.

The best Olson time zone name for North Carolina is "America/New_York", I believe.

Note that you shouldn't just add the raw offset of a time zone to a UTC time - you should set the time zone of the formatter instead. A Date value doesn't really know about a time zone... it's always just milliseconds since January 1st 1970 UTC.

So you can use:

import java.text.; import java.util.;

Date date = new Date();
DateFormat format = new SimpleDateFormat("dd/MM/yy h:mm a zzz");

format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Eastern: " + format.format(date));

format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UTC: " + format.format(date));

Output:

Eastern: 11/05/11 11:30 AM EDT
UTC: 11/05/11 3:30 PM UTC

I'd also recommend that you look into using java.time now - which is much, mnuch better than the java.util classes.

like image 118
Jon Skeet Avatar answered Sep 17 '22 02:09

Jon Skeet


according this post you habe to write TimeZone.getTimeZone("ETS") instead of TimeZone.getTimeZone("ET")

like image 29
Reporter Avatar answered Sep 19 '22 02:09

Reporter