【问题标题】:Converting a DateTime to Utc given a timezone在给定时区的情况下将 DateTime 转换为 Utc
【发布时间】:2013-03-02 17:15:09
【问题描述】:

我不想每次更改夏令时时都必须更改配置。这是我目前正在做的事情,因为它使用“标准”时间,所以它不起作用。

TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time")
TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone); // This doesn't take into account that it's daylight savings...

是否有一种万能的解决方案。所以我可以给它一个日期时间和一个像“美国东海岸”这样的位置,它给我在 Utc 的时间?

【问题讨论】:

  • 问题是什么?你能更详细地解释你的问题吗? “不起作用”是什么意思?
  • 由于夏令时,现在要休息 1 小时。
  • 我无法重现该问题 - 您确定 dateTime 设置正确吗?
  • 输入时间 7.50am 应该会导致 11.50am,但它会导致 12.50pm。
  • 当前(因为 DST 在 3 月 10 日启用)US Eastern Standard Time 的偏移量是 -5。您确定输入日期在US Eastern Standard Time 时区吗?

标签: c# .net datetime utc


【解决方案1】:

我之前通过使用映射表将时区 ID 存储在数据库中来完成此操作。即包含TimeZone.GetSystemTimeZones()结果的表格

您实际上并不需要使用 TimeZoneInfo.FindSystemTimeZoneById():您可以使用 TimeZoneInfo.ConvertTimeBySystemTimeZoneId() 的重载之一进行转换。此方法有一些采用 DateTime 值的重载,还有一些采用 DateTimeOffset 值的重载(因为它们指定了明确的时间点,所以更可取)。

例如

TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "New Zealand Standard Time", "UTC")

使用系统时区 ID 而不是存储在数据库中的偏移量的真正好处是,TimeZoneInfo.ConvertTimeBySystemTimeZoneId 会自动为您处理夏令时。

这个 msdn 也可能对你有帮助>

http://msdn.microsoft.com/en-us/library/bb382058.aspx

【讨论】:

  • 输入时间 7.50am 应该会导致 11.50am,但它会导致 12.50pm。
【解决方案2】:

您可以传递位置的 DateTime 和 TimeZone 并将提供的 DateTime 转换为 UTC

查看Example Here

       string DisplayName = "custom standard name here";//custom Standard Name to display eg: Kathmandu
       string StandardName = "custom standard name here"; // custom Standard Name eg: Asia/Kathamandu, Nepal
       string YourDate="27-03-2019 20:24:56"; // this DateTime doesn't contain any timeZone
       TimeSpan Offset = new TimeSpan(+5, 30, 00);// your TimeZone offset eg: timeZone of Nepal is +5:45
       TimeZoneInfo TimeZone = TimeZoneInfo.CreateCustomTimeZone(StandardName, Offset, DisplayName, StandardName);
       var RawDateTime = DateTime.SpecifyKind(DateTime.Parse(YourDate), DateTimeKind.Unspecified);// I all it RawDateTime Since it doesn't contain any TimeSpan
       DateTime UTCDateTime = TimeZoneInfo.ConvertTimeToUtc(RawDateTime, TimeZone);
       Console.WriteLine(UTCDateTime);

【讨论】:

    猜你喜欢
    • 2019-11-17
    • 2020-11-24
    • 2011-02-02
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2018-06-27
    相关资源
    最近更新 更多