服务器和客户端之间的日期时间差异

发布于 2024-11-04 21:47:37 字数 1824 浏览 4 评论 0原文

每个人! 我正在解决 ASP.NET MVC 项目中的下一个时间问题:

问题:需要计算客户端 DateTime 和服务器 DateTime 之间的差异。 我有 javascript 函数,它使用 timeStamp 参数 = getNow() 对服务器(DateController)进行 Ajax 查询,其代码如下。

   getNow: function() {
        var date = new Date();
        return (date.getTime() + (date.getTimezoneOffset() * 60000));
    }

接下来,在服务器端我有 DateController,其中我需要计算以毫秒为单位的日期时间差:

     ....
     var clientMs = long.Parse(Request.QueryString["t"]);
     var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);
     var msFrom1970 = (DateTime.Now - dt1970).TotalMilliseconds
            +(DateTime.UtcNow - DateTime.Now).TotalMilliseconds;
     var timeOffset = msFrom1970 -clientMs; 

     return new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { responseText = timeOffset.ToString() 
        };
     }

但是 timeOffset 计算错误。我尝试在小型控制台应用程序中检查此逻辑:

 class Program
{
    static void Main(string[] args)
    {
         var clientMs =  1304411645875; 
        //value  of clientMs I get from javaScript by using page
        //http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_gettime
        //with this script
         /*
         <HTML>
         <body>
           <script type="text/javascript">
           var d=new Date();
            document.write(d.getTime());
           </script>
          </body>
         </HTML>
         */



        var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);
        var msFrom1970 = (DateTime.Now - dt1970).TotalMilliseconds
            +(DateTime.UtcNow - DateTime.Now).TotalMilliseconds;
        Console.WriteLine( msFrom1970);
        Console.ReadLine();
    }
}

差异约为几个小时。 有人可以告诉我我的错误或问题是由其他原因引起的吗?

everyone!
I'm solving next problem with time in my ASP.NET MVC project:

Problem: need to calculate difference between client DateTime and server DateTime.
I have javascript function, that do Ajax query to server (DateController) with timeStamp parameter = getNow(), code of which is below.

   getNow: function() {
        var date = new Date();
        return (date.getTime() + (date.getTimezoneOffset() * 60000));
    }

Next, on server side I have DateController, in which I need to calculate dateTime difference in milliseconds:

     ....
     var clientMs = long.Parse(Request.QueryString["t"]);
     var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);
     var msFrom1970 = (DateTime.Now - dt1970).TotalMilliseconds
            +(DateTime.UtcNow - DateTime.Now).TotalMilliseconds;
     var timeOffset = msFrom1970 -clientMs; 

     return new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { responseText = timeOffset.ToString() 
        };
     }

But timeOffset is calculated wrong. I try to check this logic in small console app:

 class Program
{
    static void Main(string[] args)
    {
         var clientMs =  1304411645875; 
        //value  of clientMs I get from javaScript by using page
        //http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_gettime
        //with this script
         /*
         <HTML>
         <body>
           <script type="text/javascript">
           var d=new Date();
            document.write(d.getTime());
           </script>
          </body>
         </HTML>
         */



        var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0);
        var msFrom1970 = (DateTime.Now - dt1970).TotalMilliseconds
            +(DateTime.UtcNow - DateTime.Now).TotalMilliseconds;
        Console.WriteLine( msFrom1970);
        Console.ReadLine();
    }
}

Difference is about hours.
Can someone show me my mistake or problem is occurred by something else?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

永不分离 2024-11-11 21:47:38

您似乎在努力将 javascript 日期转换为 C# 日期。

[更新] getUTCMilliseconds() 只返回日期的毫秒部分 [/更新]
要将日期(以毫秒为单位)传递给服务器,请使用以下函数:

getNow: function() {
    var date = new Date();
    return date.getUTCMilliseconds();
}


并将 UTC 毫秒值转换为 .NET 中的日期时间:

// Convert UTC milliseconds to System.DateTime
DateTime dtClient = new DateTime((millisecondsClient * TimeSpan.TicksPerMillisecond) + 621355968000000000);

// Test if this conversion is correct:
TimeSpan offset = DateTime.UtcNow - dtClient;

您似乎缺少的是从毫秒到刻度的转换。

参考资料:
http://www.w3schools.com/jsref/jsref_getUTCMilliseconds.asp
http://twit88.com/blog/2011/01/ 23/net-datetime-from-milliseconds/

You seem to be struggling with converting a javascript date to a C# date.

[Update] getUTCMilliseconds() only returns the milliseconds part of a date [/Update]
To pass the date in milliseconds to the server, use this function:

getNow: function() {
    var date = new Date();
    return date.getUTCMilliseconds();
}


And to convert this value of UTC milliseconds to a DateTime in .NET:

// Convert UTC milliseconds to System.DateTime
DateTime dtClient = new DateTime((millisecondsClient * TimeSpan.TicksPerMillisecond) + 621355968000000000);

// Test if this conversion is correct:
TimeSpan offset = DateTime.UtcNow - dtClient;

What you seem to be missing is the conversion from milliseconds to ticks.

References:
http://www.w3schools.com/jsref/jsref_getUTCMilliseconds.asp
http://twit88.com/blog/2011/01/23/net-datetime-from-milliseconds/

溺渁∝ 2024-11-11 21:47:38

即使对于给定的区域设置,夏令时也会阻止函数的 getTimezoneOffset() 返回值成为常量。

Daylight savings time prevents function's getTimezoneOffset() return from being a constant even for a given locale.

油饼 2024-11-11 21:47:38

也许 DateTime.Now 大于 DateTime.UtcNow 并且 (DateTime.UtcNow - DateTime.Now).TotalMilliseconds 返回 0

Maybe DateTime.Now greater than DateTime.UtcNow and (DateTime.UtcNow - DateTime.Now).TotalMilliseconds returns 0

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文