Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Java and Javascript on 1st Jan 0001 UTC

I have a difference of how the date 1st Jan 0001 UTC is represented in Java and in Javascript

In Java:

TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(utcTimeZone);
cal.clear();
//1st Jan 0001
cal.set(1, 0, 1);
Date date = cal.getTime();
System.out.println(date);//Sat Jan 01 00:00:00 GMT 1
System.out.println(date.getTime());// -62135769600000

In JavaScript:

var date = new Date();
date.setTime(-62135769600000);
date.toUTCString(); //"Sat, 30 Dec 0 00:00:00 GMT"

Why the date, 1 Jan 0001 UTC, that is represented by the time -62135769600000L in Java, is not represented as 1st of January when displayed in Javascript?

like image 895
Xavier Delamotte Avatar asked Jun 02 '14 13:06

Xavier Delamotte


1 Answers

It looks like this is because GregorianCalendar in Java is actually a hybrid between the Gregorian calendar and the Julian calendar:

GregorianCalendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian calendar was instituted (October 15, 1582 in some countries, later in others). The cutover date may be changed by the caller by calling setGregorianChange().

If you take 1500-01-01 for example, the Java and Javascript values will be 10 days apart.

To make it a pure GregorianCalendar, you can use this:

GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
cal.setGregorianChange(new Date(Long.MIN_VALUE));

then you get a value of -62135596800000 for 0001-01-01, which gives the same date for Javascript.

Cutover calendars are a pain in the neck - they make all kinds of things odd, and are almost never useful. (I suspect that use cases where they are appropriate may have different requirements, too. I decided not to implement it for Noda Time in the end :)

like image 121
Jon Skeet Avatar answered Oct 04 '22 03:10

Jon Skeet