Have 48 Hours difference, converting C# Ticks to Java Timestamp

1k views Asked by At

According to MSDN, System.DateTime.Ticks "represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar)".

There's a internal field in DateTime, UnixEpoch, with the value 621355968000000000L which should correspond to the Unix Epoch (midnight, January 1, 1970 UTC). (We can get the same value from new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);.)

I'm trying to create a Date in Java based on a C# ticks value:

Here's a simple Java example to reproduce the problem:

    //C# System.DateTime.UnixEpoch = 621355968000000000;

    //Java code:
    //before Unix Epoch, in milliseconds
    Date date = new Date(-621355968000000000L / 10000);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    df.format(date); // 0001-01-03 00:00:00.000 +0000

Is there a kind of gap in Gregorian calendar, which is taken into account only by one of platforms?

1

There are 1 answers

0
Jonas Elfström On

It seems Java Date uses the Julian Calendar for dates when that calendar was used while C#, in this case, uses Gregorian Calendar back before there was one. By default Joda-Time also uses the Gregorian Calendar back in time.

This seems to work but there's probably a better way.

DateTime dt = new DateTime(-621355968000000000L / 10000);
GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.YEAR, dt.getYear());
gc.set(GregorianCalendar.MONTH, dt.getMonthOfYear() - 1);
gc.set(GregorianCalendar.DAY_OF_MONTH, dt.getDayOfMonth());
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);

Date date = gc.getTime();