zholmes1
zholmes1

Reputation: 609

Convert timestamp coming from a known time zone to the system's time zone

dateFormatterLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormatterLocal.setTimeZone(TimeZone.getTimeZone("America/New York"));
for (int i = 0; i < list.length; i++) {
    timeStampArrayList.add(dateFormatterLocal.parse(list[i]));
}

My current code is not converting the timestamp that is known to be in UTC time zone to my time zone.

I would also like to know how to get the system's current time zone instead of having to tell it "America/New York" if possible.

Thanks in advance!

Upvotes: 0

Views: 929

Answers (1)

Java Devil
Java Devil

Reputation: 10969

I'm not sure I completely understand your problem either but here is my best effort to answer it for you.

I assume you have a date as a string which is in UTC timezone and you want the date as the systems (or your local) timezone.

To do this simply add the String " UTC" to your time string and change your date formatter pattern to "yyyy-MM-dd HH:mm:ss Z". Here Z is RFC 822 time zone. You could also use z which is General time zone.

So your code would become:

String timezoneOffset = " UTC";
dateFormatterLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");  
dateFormatterLocal.setTimeZone(TimeZone.getTimeZone("America/New York"));
for (int i = 0; i < list.length; i++) {
   timeStampArrayList.add(dateFormatterLocal.parse(list[i] + timezoneOffset ));
}

This should then parse the date to the time zone of the formatter converted from the time zone string provided.


You can do this to get the Systems current timezone

TimeZone timeZone = Calendar.getInstance().getTimeZone();
System.out.println(timeZone.getDisplayName(false, TimeZone.LONG));

Which prints New Zealand Standard Time for me - which is the current timezone.

You can also change TimeZone.LONG to TimeZone.SHORT to get the abbreviated version i.e. I get NZST


Also you should read this question and answer about displaying Date

Upvotes: 1

Related Questions