英文:
C# DateTimeOffset bad hour. Difference TimeSpan to DateTime and DateTime to TimeSpan
问题
u_date = 1688066111
结果: 1688066111
DateTime p_date = DateTimeOffset.FromUnixTimeSeconds(u_date).DateTime;
结果: 生成:2023-06-29 19:15:11
long unixTime = ((DateTimeOffset)p_date).ToUnixTimeSeconds();
结果: 生成:1688066111 (2023-06-29 19:15:11)
如何解决这个问题?
英文:
u_date = 1688066111
DateTime p_date = DateTimeOffset.FromUnixTimeSeconds(u_date).DateTime;
Gives: 2023-06-29 19:15:11
long unixTime = ((DateTimeOffset)p_date).ToUnixTimeSeconds();
Gives: 1688058911 (2023-06-29 17:15:11)
How to fix that problem?
答案1
得分: 3
-
DateTimeOffset.FromUnixTimeSeconds(u_date)将给您
2023-06-29 19:15:11 +00:00,即一个UTC日期/时间。
参考链接 -
获取属性
DateTime将擦除时区信息
(结果的 p_date 具有DateTimeKind.Unspecified)。
参考链接 -
((DateTimeOffset)p_date)将解释 p_date 为本地时间,即
在您的情况下似乎是+02:00的当前时区。
参考链接
您可以通过避免通过 DateTime 进行往返来修复此问题,仅使用 DateTimeOffset。或者 - 如Jon在评论中提到的 - 在步骤2中使用属性 UtcDateTime(而不是 DateTime),这将产生一个具有 DateTimeKind.Utc(而不是 DateTimeKind.Unspecified)的 DateTime 对象。
英文:
Doing it step by step will reveal what happens:
-
DateTimeOffset.FromUnixTimeSeconds(u_date)will give you
2023-06-29 19:15:11 +00:00, i.e. a date/time in UTC.
Reference -
Getting the property
DateTimewill erase the time zone information
(the resulting p_date hasDateTimeKind.Unspecified).
Reference -
((DateTimeOffset)p_date)will interpret p_date as local time, i.e.
in the current timezone which seems to be +02:00 in your case.
Reference
You can fix this problem by avoiding the round-trip via DateTime, using only DateTimeOffset. Or - as Jon noted in his comment - by using the property UtcDateTime in step 2 (instead of DateTime) which will produce a a DateTime object with DateTimeKind.Utc (instead of DateTimeKind.Unspecified).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论