I am having trouble with converting old dates from java.time.LocalDateTime to java.util.Date
I tried a lot of variation and it still has the same shifted dates. I would assume that it is some weird calendar performed but it is failing.
Date to parse 1800-01-01 00:00:00
I used a very simple convert function.
Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
TimeZone | a.Converted via SimpleDateFormat | b.Converted via DateFormatter to LocalDateTime to java.util.Date |
---|---|---|
Asia/Tokyo | 1800-01-01 00:00:00 JST | 1799-12-31 23:41:01 JST |
Europe/Brussels | 1800-01-01 00:00:00 CET | 1800-01-01 00:04:30 CET |
Australia/Sydney | 1800-01-01 00:00:00 AEST | 1799-12-31 23:55:08 AEST |
UTC | 1800-01-01 00:00:00 UTC | 1800-01-01 00:00:00 UTC |
a. Convert String to java.util.Date via SimpleDateFormat
b. Convert String to java.time.LocalDatetime via DateFormatter, then convert it to java.util.Date
Now I see it only works for the UTC timezone, I cannot just change the software timezone as it will mess with the others. Anyone know any other way to convert a java.time.LocalDateTime to java.util.Date for an old day?
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
===== following is added after sweeper's answer to illustrate it is not for all ====
The curious thing is it only happens to really old dates, it does not happen to 1900-01-01 00:00:00 but have not check yet at which point the trouble started. I was thinking that maybe because of and adjustment / change at some point in 18XX year.
System.out.println(ZoneId.of("Asia/Tokyo").getRules().getOffset(LocalDateTime.parse("1800-01-01T00:00:00")));
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(TimeZone.getTimeZone("Asia/Tokyo").getOffset(format1.parse("1800-01-01T00:00:00").getTime()));
System.out.println(ZoneId.of("Asia/Tokyo").getRules().getOffset(LocalDateTime.parse("1900-01-01T00:00:00")));
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(TimeZone.getTimeZone("Asia/Tokyo").getOffset(format2.parse("1900-01-01T00:00:00").getTime()));
Results to
+09:18:59
32400000
+09:00
32400000
java.util.Date
, like for a legacy API that you cannot upgrade? Otherwise you should simply avoid that old class. AndTimeZone
andSimpleDateFormat
. java.time, the modern date and time API to whichLocalDateTime
belongs, gives you all the functionality you wish for. – Similar