admin管理员组

文章数量:1308200

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

According to , 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 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?

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

According to https://developer.mozilla/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 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?

Share Improve this question asked Mar 1, 2012 at 19:58 Vivian RiverVivian River 32.4k64 gold badges210 silver badges323 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

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;

someDate.Ticks is measured since January 1st, 0001.

Javascript dates take milliseconds since January 1st, 1970, UTC.

That's because the DateTime structure counts ticks since 0001-01-01, while the Date object counts milliseconds since 1970-01-01.

Take the difference from 1970-01-01 as milliseconds:

ViewBag.x = (someDate - new DateTime(1970, 1, 1)).TotalMilliseconds;

The Unix calender's epoch is 1970-01-01 00:00:00 UTC. Assuming your times are already UTC (not a given):

DateTime someDate   = GetSomeDate() ;
DateTime UNIX_EPOCH = new DateTime(1970,1,1) ;
Timespan ts         = someDate - UNIX_EPOCH ;

should do you. Then pass javascript, the TimeSpan's TotalMilliseconds property.

Rules:

C# Ticks measures since 0001-01-01.

Javascript dates take milliseconds since 1970-01-01, UTC.

Then you need subtract 2665800000 milliseconds from your C# DateTime variable (someDate):

2665800000 is a const: different between 1970-01-01 and 0001-01-01 as milliseconds

Use:

ViewBag.x = (someDate - new DateTime(2665800000)).TotalMilliseconds;

本文标签: netWhy can39t I convert milliseconds from C to a JavaScript Date ObjectStack Overflow