C#与Unix时间相互转换-损失了1天
c#
这是代码:
var date = DateTime.Now.Date;
var ms = (long)(date - DateTimeOffset.UnixEpoch).TotalMilliseconds;
var date1 = DateTimeOffset.FromUnixTimeMilliseconds(ms).DateTime.Date;
日期是 24 日,日期 1 是 23 日
他们为什么不匹配?
回答
使用DateTimeOffset.FromUnixTimeMilliseconds(ms).LocalDateTime.
DateTime.Now有Kind = Local所以它正在偏离你的 UTC 偏移量。
你可以看到它:
var kind = DateTime.Now.Date.Kind;
然后你可以用“种类”做一个小测试:
var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
var ms = (long)(date - DateTimeOffset.UnixEpoch).TotalMilliseconds;
多少钱ms?根据冬季/夏季时间和您的位置,它可能不是 0。
所以你ms包括你的UTC偏移量。现在你必须:
var date1 = DateTimeOffset.FromUnixTimeMilliseconds(ms).LocalDateTime;
让我们希望您仍处于“原始”UTC 偏移量中(因此在 的计算date和 计算之间没有足够的天数让date1您在冬/夏时间之间切换)
(如果你做的一切都正确,你真的不需要.Dateafter .LocalDateTime,因为日期应该已经是00:00:00)
- @BoppityBop And those two hours push the 00:00 time to 22:00 time of the day previous. There is no "pure Date" type in C#. With the `.Date` you simply put the time to 00:00.
- As a rant, the Kind information in DateTime is one of the worst ideas they put in .NET 1.0, and sadly we have to keep it. I've only seen it break things, and I haven't ever seen it as something useful.
- @BoppityBop Exactly. Don't forget you're doing `DateTime.Now.Date` -- that `.Date` is important, as it gives you a `DateTime` representing midnight on the day in question