I have legacy code that uses java.util.Date creating an ancient date (30 Nov 0002). I'm trying to update what code I can, but that's necessitating converting between Date and LocalDate, etc. I can't completely get rid of the use of Date or the ancient date choice.
I'm finding what appears to be an error when converting back and forth between Date and Instant with this ancient date, and was hoping someone could explain what is going on.
Here's a sample:
Date date = new Date();
Instant instant = date.toInstant();
System.out.println("Current:");
System.out.println("Date: "+date);
System.out.println("Instant: "+instant);
System.out.println("Date epoch: "+date.getTime());
System.out.println("Instant epoch: "+instant.getEpochSecond()*1000);
System.out.println("\nAncient from Date:");
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("MST"));
cal.set(2, Calendar.NOVEMBER, 30, 0, 0, 0);
date = cal.getTime();
instant = date.toInstant();
System.out.println("Date: "+date);
System.out.println("Instant: "+instant);
System.out.println("Date epoch: "+date.getTime());
System.out.println("Instant epoch: "+instant.getEpochSecond()*1000);
System.out.println("\nAncient from Instant:");
instant = Instant.parse("0002-11-30T00:00:00Z");
date = Date.from(instant);
System.out.println("Date: "+date);
System.out.println("Instant: "+instant);
System.out.println("Date epoch: "+date.getTime());
System.out.println("Instant epoch: "+instant.getEpochSecond()*1000);
Which prints the following:
Current:
Date: Tue Sep 18 12:34:27 MST 2018
Instant: 2018-09-18T19:34:27.177Z
Date epoch: 1537299267177
Instant epoch: 1537299267000
Ancient from Date:
Date: Thu Nov 30 00:00:00 MST 2
Instant: 0002-11-28T07:00:00.247Z
Date epoch: -62075437199753
Instant epoch: -62075437200000
Ancient from Instant:
Date: Fri Dec 01 17:00:00 MST 2
Instant: 0002-11-30T00:00:00Z
Date epoch: -62075289600000
Instant epoch: -62075289600000
So if I create an Instant at 30 Nov 2, then convert to a Date, the Date is 1 Dec 2. If I start with a Date at 30 Nov 2, the Instant is 28 Nov 2. I'm aware that neither Date nor Instant store timezone information, but why are the epochs so different based on whether I started with a Date vs. an Instant? Is there anyway I can work around that? I need to be able to start with either a Date or an Instant, and end up with the same epoch value. It would also be nice to know why the default toString() shows such different dates given the same epoch.