Daniel Allen Langdon Daniel Allen Langdon - 1 year ago 81
Javascript Question

Why can't I convert milliseconds from C# to a JavaScript Date Object?

I've written a function in .net that returns a date. I need to get that date into a Date Object in JavaScript.

According to https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date, I should be able to invoke

new Date(x)
where x is the number of milliseconds in my date.

Therefore, I've written the following in my ASP.net MVC 3 code:

ViewBag.x = new TimeSpan(someDate.Ticks).TotalMilliseconds;

Then, in JavaScript, I get the following code:

new Date( 63461023004794 )

The date being represented should be January 1st, 2012.

However, the date that JavaScript reads is December 31st, 3980.

What's going wrong here?

Answer Source

Your .NET code is giving you the number of milliseconds since Jan. 1st, 0001.

The JavaScript constructor takes the number of milliseconds since Jan. 1st, 1970.

The easiest thing would probably be to change your .NET code to:

ViewBag.x = (someDate - new DateTime(1970, 1, 1)).TotalMilliseconds;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download