Search code examples
javac#timestamp-with-timezone

C# DateTime in Java


I am trying to convert millseconds to time in Java.

when I do this in C#

DateTime EpochOrigin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

Console.WriteLine("1406205185123 = " + EpochOrigin.AddMilliseconds(1406205185123));

result 24/07/2014 12:33:05

when I do same in Java

 Calendar cc = new GregorianCalendar();

cc.setTimeInMillis(1406205185123L);

result Thu Jul 24 13:33:05 BST 2014

The Java result add 1 more hour than C# .

Any suggestion how can I fix this?


Solution

  • In C# DateTime doesn't store time zone information, but has a Kind property whose value indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neithee (see MSDN). The default value of DateTime.Kind property is Unspecified. Therefore, in your C# code, a DateTime structure created with the line

    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    

    should definitely be created in this way:

    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    

    in order to be used as the reference time for the conversion (Epoch time origin is January 1, 1970, 00:00 UTC).

    More information can be found in this previous question: https://stackoverflow.com/a/2883645/1236452.

    Edit 1

    A quick remark: DateTime in C# is somehow aware of the time zone (my local time is GMT+1)(edit: please refer to comments and Edit 2):

    DateTime t = new DateTime(1970,1,1,0,0,0);
    Console.WriteLine(t.ToLocalTime());      // 01/01/1970 01:00:00 (GMT+1)
    Console.WriteLine(t.ToUniversalTime());  // 31/12/1969 23:00:00 (GMT)
    

    Edit 2

    As correctly pointed out in the comments, DateTime is not aware of the time zone in the sense that it holds the time zone information. However, in its Kind property it does store a value that indicates whether the instance is based on local time or UTC, as stated in the documentation:

    DateTime.Kind Property: Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. [...]

    The Kind property allows a DateTime value to clearly reflect either Coordinated Universal Time (UTC) or the local time. In contrast, the DateTimeOffset structure can unambiguously reflect any time in any time zone as a single point in time.