我正在开发一个小型电子商务,其中客户主服务器将 Date
作为 GET
参数以秒的形式发送。基于此,我必须检查从他们发送的 Date
分钟在当前 DateTime
中是否不超过 20
分钟。
目前的问题是 C# DateTime
总是比服务器发送的 Date
早 3 小时。
如果我执行 new Date(2018, 4, 3, 12, 25, 00).getTime()/1000
(从纪元获取秒数)并将其传递给我的 DateTime
在服务器端 我总是提前 3 小时,所以在这个例子中我得到 03-05-2018 09:25:00
这就是我在服务器中解析Date
的方式
DateTime sDt = (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local))
.AddSeconds(double.Parse(sessionDs.Tables[0].Rows[0]["DT"].ToString()));
DataColumn
的值是从 JS Date
算起的秒数
这是为什么呢?我错过了什么?
最佳答案
Javascript Date.getTime
使用 UTC,如文档所述:
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.
所以你应该像这样调整你的 C# 代码:
DateTime sDt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) // <
.AddSeconds(yourJsNumber).ToLocalTime();
如果您不需要本地时区的日期,您可以省略 ToLocalTime
并在 UTC 中使用它。
关于javascript - JS Date seconds 在 c# 中给出不同的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152942/