Search code examples
javatimezonedstjava.util.date

Convert unix timestamp between different timezones and different DST in Java


PROBLEM SOLVED External device was computing and sending non-standard 2 hours shifted timestamp, which hugely confused me and started this thread. TIMESTAMP BY ITSELF IS NOT AFFECTED BY TIMEZONES , timezones apply only when converting in/from human readable forms.


I have timestamp (seconds from unix epoch) in UTC timezone - no DST (daylight saving time).

I want timestamp (seconds from unix epoch) in "Europe/Prague" timezone, that uses DST.

I used to think that unix timestamp is unbound by timezones, that timezones affect only process of converting timestamp to human readable formats. But it doesn't look like that. And the more I am trying to convert it (using Calendar and TimeZone classes), the more confused and lost I am getting.

this code DOES NOT work as expected:

Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(ts*1000);
cal.setTimeZone(TimeZone.getTimeZone("Europe/Prague"));
return cal.getTimeInMillis()/1000;

Solution

  • There is not a way to "convert" a timestamp, it is always the number of milliseconds from the epoch.

    You can use a DateFormat to format the timestamp into a format with a time zone applied, or use a Calendar to look at the hours, minutes, and seconds with a time zone applied.

    getTimeInMillis() gets the timestamp back just the same as you put it in, the number of milliseconds from the epoch: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#getTimeInMillis%28%29