简体   繁体   English

将日期从JavaScript转换为服务器端的问题

[英]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: JavaScript日期:

    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. 现在,我通过ajax将上述字符串(1301700600000)传递到服务器端代码。 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. 即Fri Apr 01 2011 05:00:00 GMT + 0530不等于{3/31/2011 12:00:00 AM}注意日期和时间差。

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? 如何从毫秒创建TimeSapn? Call TimeSpan.FromMilliseconds http://msdn.microsoft.com/en-us/library/system.timespan.frommilliseconds.aspx 致电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. 注意:请考虑使用UTC版本的函数来获取日期和时间值。 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. 为什么不简单地传递Date字符串并在服务器上解析它。

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. 更好的解决方案是计算UTC时间与客户端本地时间之间的时差并将其发送到服务器。 Round it to half hours (is there a smaller timespan between time zones?) and you'll have a pretty precise info. 将其舍入为半小时(时区之间的时间间隔是否更短?),您将获得非常精确的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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