In the afternoon to engage in MVC and ExtJS date format conversion encountered problems that we have from. NET Server-side serialization of a DateTime object is the result of a string format, such as '/date (1335258540000)/' strings.
The integer 1335258540000 is actually a number of milliseconds from 00:00:00 to this datetime intermediate interval of January 1, 1970. JavaScript uses the Eval function to convert this date string to a Date object with a time zone, as follows
with var date = eval (' new ' + eval ('/date (1335258540000)/'). Source) So you can get a JS object
Clear by alert (date).
Tue APR 17:09:00 utc+0800 2012
Above is the string that the C # JSON serialization date automatically gets, or you can write a function from C # to get this number, for example
Public long Millitimestamp (datetime thedate)
{
datetime d1 = new DateTime (1970, 1, 1);
DateTime D2 = Thedate.touniversaltime ();
TimeSpan ts = new TimeSpan (D2. Ticks-d1. Ticks);
return (long) TS. TotalMilliseconds;
}
The above function is the same as the integer in the string that was fetched by using JSON serialization.
However, when you return to the server side from the client, the date encounters a problem, how do you pass the JavaScript date object back to the server side?
The integer is fetched first through the gettime () in JavaScript date, and then the server resolves the integer to ' construct ' into a C # DateTime object. The idea is probably like this, but in the reverse back when there was a bit of trouble.
Public DateTime converttime (long millitime)
{
long timetricks = new DateTime (1970, 1, 1). Ticks + millitime * 10000;
return new DateTime (timetricks);
}
The results obtained by ConvertTime found that the time is less than 8 hours, which is exactly the time zone of the server, East Eight, that is, plus 8 hours of nanosecond, because C # timestamp unit is one out of 10,000 seconds, one hours 3,600 seconds, that is, 8*3600*10000000
So the ConvertTime function is modified, and the correct is as follows:
Public DateTime converttime (long millitime)
{
long timetricks = new DateTime (1970, 1, 1). Ticks + millitime * 10000 + TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now). Hours * 3600 * (long) 10000000;
return new DateTime (timetricks);
}
The above JS and C # time and date format conversion Simple example is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.