【问题标题】:Is there a way to convert from timezone format (America/Chicago) to UTC (-0500) in C# .net?有没有办法在 C# .net 中将时区格式(美国/芝加哥)转换为 UTC(-0500)?
【发布时间】:2021-07-01 15:46:40
【问题描述】:

我得到了一组时区名称,需要将它们用作 UTC 偏移量。有没有办法进行这种转换以获得当前的 UTC 偏移量(包括适当的 DST 偏移)?

【问题讨论】:

标签: c# asp.net datetime timezone timezone-offset


【解决方案1】:

这就是 TimeZoneInfo.GetUtcOffset 方法旨在完成的任务。

DateTime utcNow = DateTime.UtcNow;
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("America/Chicago");
TimeSpan offset = tz.GetUtcOffset(utcNow);

如果您在 Linux 或 Mac OSX 上运行 .NET,上述内容将有效,并且将来(从 .NET 6 开始)将在 Windows 上有效。

如果您现在在 Windows 上运行 .NET,则可以使用我的 TimeZoneConverter 库,它会在获取 TimeZoneInfo 对象时在内部将 IANA 时区 ID 转换为 Windows 时区 ID。

DateTime utcNow = DateTime.UtcNow;
TimeZoneInfo tz = TZConvert.GetTimeZoneInfo("America/Chicago");
TimeSpan offset = tz.GetUtcOffset(utcNow);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2012-10-21
    • 2021-02-28
    • 2012-05-03
    相关资源
    最近更新 更多