Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime precision difference .NET vs Java

Im porting some calculation routines from .Net to Java but there seem to be some precision problems in the Date classes. Maybe I have stared myself blind on this but I cant figure out why the results differ.

How should I handle the dates to get the same numbers (milliseconds) across the platforms?

.Net

[Test] public void foo() {
    DateTime dt1 = new DateTime(2011, 2, 26, 19, 25, 24);
    DateTime dt2 = new DateTime(2011, 2, 28, 18, 40, 25);
    double millis = (dt2 - dt1).TotalMilliseconds;
    Assert.AreEqual(170101000, millis);
}

Java

@Test public void foo() throws Exception {
    Date d1 = createDate(2011, 2, 26, 19, 25, 24);
    Date d2 = createDate(2011, 2, 28, 18, 40, 25);
    long millis = d2.getTime() - d1.getTime();
    Assert.assertEquals(166501000, millis, 0.01);
}

private static Date createDate(int year, int month, int day,
        int hour, int minute, int second) {
    Calendar instance = Calendar.getInstance();
    instance.clear();
    instance.set(year, month, day, hour, minute, second);
    return instance.getTime();
}
like image 838
Mizipzor Avatar asked Jan 19 '23 18:01

Mizipzor


2 Answers

Wonderful!

Problem:

Java Calendar months start at 0 and .Net Datetime months start at 1.

So you are comparing .Net february to Java march. And, as Arjan suggested, on march 27th is the change to daylight savings time in many timezones.

This is a very common problem when using Java Calendar. To avoid it, you should use the named constants for the months like this:

Date d1 = createDate(2011, Calendar.MARCH, 26, 19, 25, 24); // Calendar.MARCH == 2
like image 122
Arend v. Reinersdorff Avatar answered Jan 28 '23 02:01

Arend v. Reinersdorff


The difference in milliseconds is 3,600,000, so exactly 1 hour. Could it be that one language is using a different timezone setting than the other, where there is a change from or to DST?

I have done some more testing. The PHP result matches the C# result (only I get seconds instead of milliseconds) and my Java result matches your Java result. The problem seems to be a bug in the timezone handling in Java. According to Java the second time is in DST, which is not correct in my timezone (Europe/Amsterdam).

like image 24
Arjan Avatar answered Jan 28 '23 00:01

Arjan