C# DateTimeOffset 错误的小时。将 TimeSpan 转换为 DateTime 和 DateTime 转换为 TimeSpan

huangapple go评论88阅读模式
英文:

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

  1. DateTimeOffset.FromUnixTimeSeconds(u_date) 将给您
    2023-06-29 19:15:11 +00:00,即一个UTC日期/时间。
    参考链接

  2. 获取属性 DateTime 将擦除时区信息
    (结果的 p_date 具有 DateTimeKind.Unspecified)。
    参考链接

  3. ((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:

  1. DateTimeOffset.FromUnixTimeSeconds(u_date) will give you
    2023-06-29 19:15:11 +00:00, i.e. a date/time in UTC.
    Reference

  2. Getting the property DateTime will erase the time zone information
    (the resulting p_date has DateTimeKind.Unspecified).
    Reference

  3. ((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).

huangapple
  • 本文由 发表于 2023年7月6日 13:40:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定