I want to convert ms-since-1970-timestamp
to a date with timezone (Germany).
Here are two variants of code which worked - at least, I remember using it
I believe the problem is the default timezone on the platform you're running on.
java.util.Date()
does have a time zone. It maintains "inherited" time zone information, which, it appears, is acquired from the system's default locale.
this code.
TimeZone tz = TimeZone.getTimeZone("GMT-03:00");
Calendar cal = Calendar.getInstance(tz);
cal.set(1953, 2, 22, 4, 20, 13);
Date dateTime = cal.getTime();
System.out.println(dateTime.toString());
yields this on my system, which is uses the PST locale: Sat Mar 21 23:20:13 PST 1953.
I don't believe that there is a way to use the java.util.Date object
, or the DateFormat objects which use it, to accurately handle time information from a "foreign" time zone.
This is the problem:
TimeZone.getTimeZone("Germany")
There's no such time zone ID, so Java in its infinite wisdom decides to just return you UTC without telling you that anything's wrong. Try this instead:
TimeZone.getTimeZone("Europe/Berlin")
Wikipedia has a list of IANA time zone IDs, but it's somewhat out of date (at the time of writing); the IANA data is the most up-to-date, but it's not as easily browsable...
The Answer by Jon Skeet is correct, you used an incorrect time zone name.
Here is a solution using the modern java.time classes that supplant the old legacy date-time classes that have proven to be so troublesome and confusing.
Instant instant = Instant.ofEpochMilli( milliseconds_since_1970 ); // Or Instant.now() for current moment.
ZoneId z = ZoneId.of( "Europe/Berlin" );
ZonedDateTime zdt = instant.atZone( z );
Generate a localized string to represent that date-time value.
Locale l = Locale.GERMANY; // Or Locale.CANADA_FRENCH, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT ).withLocale( l );
String output = zdt.format( f );