0

I'm using .NET to generate a JSON file that has many Dates in it.

For compression, I want to store them as milliseconds since Jan 1, 1970 and not strings, then convert them to Javascript Dates. But .Net's idea of milliseconds since 1970年01月01日 don't match Javascript:

Javascript:

Date.parse("2012-05-15T13:57:57.0000000+00:00")
1337090277000

VB.Net:

Date.Parse("2012-05-15T13:57:57.0000000+00:00").Subtract(New Date(1970,1,1)).TotalMilliseconds
1337101077000.0

The difference is 10800 seconds. The difference at 1970年01月01日 is 0 and changes over time.

Is there a way to compute Javascript's idea of milliseconds-since-epoch from within .Net?

asked Jul 28, 2012 at 13:03
1
  • The difference is 3 hours exactly. Perhaps the original time was from a different time zone? Commented Jul 28, 2012 at 13:09

1 Answer 1

4

You are comparing apples to oranges.

This is exactly what you would get in javascript as well when in UTC+3 (Israel):

Date.parse("2012-05-15T13:57:57.0000000+00:00") - new Date(1970,1,1)
//1334419077000

This is because when you do new Date in javascript, that's according to the machine's timezone. It looks like it's the same for vb.net.


You would get the correct number in javascript with:

Date.parse("2012-05-15T13:57:57.0000000+00:00") - Date.UTC(1970,1,1)
//1334411877000

In VB.net

 Dim a As Date
 a = Date.Parse("2012-05-15T13:57:57.0000000+00:00").ToUniversalTime()
 Dim b As Date
 b = New Date(1970, 2, 1, 0, 0, 0, DateTimeKind.Utc)
 a.Subtract(b).TotalMilliseconds
 '1334411877000 Same as javascript
 'Note that in javascript, month as 1 is same as 2 in VB.net because months start at 0 in javascript
answered Jul 28, 2012 at 13:29

7 Comments

Oy, of course! Replacing Date with DateTimeOffset solves my problem unambigously. I don't like giving a timezone to the Date constructor.
@Eyal Why would you want to do that? It's unnecessary moving part. UTC is always the same.
The output of your final answer is not 1334411877000.0, it's 1337101077000. ?Date.Parse("1970年01月01日T00:00:00.0000000+00:00").Subtract(New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds, by the way, is 72000000. VB.Net's Date.Parse() is ignoring the timezone.
@Eyal can you try like this: DateTime.ParseExact( "2012年05月15日T13:57:57.0000000+00:00", "yyyy-MM-ddTHH:mm:ss.fffffffZ",System.Globalization.DateTimeFormatInfo.InvariantCulture)
@Eyal or Date.Parse("2012年05月15日T13:57:57.0000000+00:00").TotalMilliSeconds - New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).TotalMilliseconds
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.