简体   繁体   中英

Issue converting the date from JavaScript to Server side

I have a date at client side, I am converting that date to millisecond there and passing the milliseconds to server side code and the converting that to again in date format, but the issue is in this process my date changes. Below is my scenario

JavaScript Date:

    var myDate= Fri Apr 01 2011 05:00:00 GMT+0530 (India Standard Time) {}
    //Converted to milliseconds via this code (new Date(myDate)).getTime()
    Output: 1301700600000

Now I am passing the above string(1301700600000) to my server side code via ajax. Below is the server side code.

private void Test(string myDate)
{
    long myDateMilliseconds=long.Parse(myDate);
    var myDate = new DateTime(1970, 1, 1) + new TimeSpan(myDateMilliseconds*10000);
    //Here the date becomes Date = {3/31/2011 12:00:00 AM}
}

ie Fri Apr 01 2011 05:00:00 GMT+0530 is not equal to {3/31/2011 12:00:00 AM} Note the date and time difference.

May I know how there is difference coming between the dates which I passed and the date which I have produced at the server.

How to create TimeSapn from milliseconds? Call TimeSpan.FromMilliseconds http://msdn.microsoft.com/en-us/library/system.timespan.frommilliseconds.aspx

Note: consider using UTC versions of functions for getting Date and Time values. And read about time zones...

Looks like you are losing the precession there. Why not simply pass the Date string and Parse it on server.

Try using

var d = new Date();
var utcMs = d.UTC();

on the client-side. Then use

var utcThen = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(clientUtcMs);

var localThen = utcThen.ToLocalTime();

A better solution would be to compute the difference between UTC time and the local time at the client and send that to the server. Round it to half hours (is there a smaller timespan between time zones?) and you'll have a pretty precise info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM