I’m trying to use SimpleDateFormat to convert between unix timestamp and a custom format and vice versa.
To test this vice versa converting I wrote the following testcase:
public class Testception extends TestCase {
public void testTheTestOrTestception() throws ParseException {
Date datum = new Date(649555200000L);
SimpleDateFormat dfm = new SimpleDateFormat("yyyy-MM-dd");
TimeZone tZ = TimeZone.getTimeZone("Europe/Berlin");
dfm.setTimeZone(tZ);
String aDifferentFormat = dfm.format(datum);
assertEquals("1990-08-02", aDifferentFormat);
Date datum2 = dfm.parse(aDifferentFormat);
assertEquals(649555200000L, datum2.getTime());
}
}
I’m starting with an unixtimestamp (649555200000), converting it in my custom format (“1990-08-02”) which is working just nicely. But unfortunately the second assert fails and instead of the expected 649555200000L the result is 649548000000L
Thanks in advance.
Cheers L0rdAli3n
It’s all to do with the time zones.
You’ve given it midnight UTC, and formatted that as a date – but it was actually 2am in Berlin time.
You’re then parsing that date which will parse to midnight on that date in Berlin, which is two hours earlier than your starting point. If you want to get midnight UTC back again, just set the time zone of your
SimpleDateFormatto the UTC time zone.