0

The following js code in Chrome dev console.

new Date(1560780000000)

yields

Tue Jun 18 2019 00:00:00 GMT+1000 (Australian Eastern Standard Time)

however in c# on the same machine, this yields

new DateTime(1970, 1, 1).AddMilliseconds(1560780000000);

17/06/2019 14:00:00

Using

new DateTime(1970, 1, 1).ToLocalTime().AddMilliseconds(1560780000000);

yields

18/06/2019 01:00:00

The date is still out by an hour. I am trying to translate a JS date into a C# DateTime accurately. I can't change the signature of the method from DateTime, can anyone help?

KH

KnowHoper
  • 4,352
  • 3
  • 39
  • 54
  • 1
    Localization and formatting, especially `.ToString(string format)`. And you can also try `new DateTime(numberOfTicks)`. – Troll the Legacy Mar 21 '19 at 08:20
  • What about `DateTimeOffset.FromUnixTimeMilliseconds(1560780000000).DateTime` does that give the correct result? What about `.UtcDateTime` instead? If not, I think the "issue" is going to come down to the handling of local datetimes (always assuming the system's current offset) – pinkfloydx33 Mar 21 '19 at 08:32

2 Answers2

2

This gives me the same result:

new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(1560780000000)

or this

new DateTime(1970, 1, 1).AddMilliseconds(1560780000000).ToLocalTime()

They are not 100% equivalent, but the second one will create a date with kind Unspecified that is assumed to be UTC when you call ToLocalTime().

The difference if you call ToLocalTime() before or after AddMilliseconds() is in Daylight Saving it seems. Depending on the date, same local time will be interpreted differently. So you should always do all calculations in UTC I assume and only convert to local time to check in the end.

The problem was that you have added milliseconds that made it to be in summer when DST would make a difference (I think ).

More details here.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
0

To get UTC timestamp in JavaScript :

new Date(1560780000000).toJSON();                                      // "2019-06-17T14:00:00.000Z"

C# :

DateTimeOffset.FromUnixTimeMilliseconds(1560780000000).ToString("o");  // "2019-06-17T14:00:00.0000000+00:00"

new DateTime(1970, 1, 1).AddMilliseconds(1560780000000).ToString("o"); // "2019-06-17T14:00:00.0000000"
Slai
  • 22,144
  • 5
  • 45
  • 53