这是基于在 C# 中计算 1970 年以来的毫秒数会产生与 JavaScript 不同的日期 https://stackoverflow.com/q/22081128/1346943 and Javascript Date.getTime() 的 C# 版本 https://stackoverflow.com/q/8134170/1346943.
对于所有这些计算,假设它们是在中部标准时间完成的,因此比 UTC 晚 6 小时(此偏移稍后会再次出现)。
我理解 JavaScriptDate
对象基于 Unix Epoch(1970 年 1 月 1 日午夜)。所以,如果我这样做:
//remember that JS months are 0-indexed, so February == 1
var d = new Date(2014,1,28);
d.getTime();
我的输出将是:
1393567200000
它代表自 Unix 纪元以来的毫秒数。这一切都很好。在链接的问题中,人们询问是否将此功能转换为 C#,“简单”的实现通常如下所示:
//the date of interest in UTC
DateTime e = new DateTime(2014, 2, 28, 0, 0, 0, DateTimeKind.Utc);
//the Unix Epoch
DateTime s = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
//the difference between the two
TimeSpan t = (e - s);
var x = t.TotalMilliseconds;
Console.WriteLine(x);
产生输出:
1393545600000
这是 21,600,000 毫秒或 6 小时的差异:完成这些计算的时区与 UTC 的精确偏移。
为了使 C# 实现与 JavaScript 匹配,实现如下:
//DateTimeKind.Unspecified
DateTime st=new DateTime(1970,1,1);
//DateTimeKind.Unspecified
DateTime e = new DateTime(2014,2,28);
//translate e to UTC, but leave st as is
TimeSpan t= (e.ToUniversalTime()-st);
var x = t.TotalMilliseconds;
Console.WriteLine(x);
这将为我提供与 JavaScript 输出匹配的输出:
1393567200000
我还没有找到解释为什么我们离开DateTime
代表 Unix 纪元DateTimeKind
of Unspecified
能够匹配JavaScript。我们不应该使用得到正确的结果吗DateTimeKind.Utc
?我不明白什么细节?这对我来说纯粹是一个学术问题,我只是好奇为什么会这样。