如何分析时区偏移量字符串

本文关键字:偏移量 字符串 时区 | 更新日期: 2023-09-27 18:33:18

我从我的数据库中检索一个时区偏移量的值。我得到的价值是及时的。

例如,它可以是"-5:00""+7:30""+3:00"等。

如何将其转换为双精度,以便我可以对DateTime对象进行AddHours()调用?

如何分析时区偏移量字符串

约翰·科尔纳的回答有几个缺点;

  • 根据+-可能需要额外的字符串操作。它可以处理-符号或没有符号,但不能处理+字符本身。
  • 由于他使用的TimeSpan.Parse(string)过载,如果CurrentCultureTimeSeparator不是:我知道这很少见),这种方法会抛出FormatException

除此之外,我认为TimeSpan.Parse不是解析 UTC 偏移量的最佳方式。实际上,Offset也是一个时间间隔,但此值可能并不总是成功解析。

我认为最好的选择是DateTimeOffset.TryParseExact带有zzz格式说明符的方法。由于DateTimeOffset.Offset属性返回它的值为 TimeSpan ,因此它完全可以与 DateTime 一起使用。

例如;

var s = "+05:30";
DateTimeOffset dto;
var dtop = DateTimeOffset.TryParseExact(s, "zzz",
                 CultureInfo.InvariantCulture,
                 DateTimeStyles.None, out dto);
var today = DateTime.Today;
today = today.AddHours(dto.Offset.TotalHours);

这适用于所有可能的 UTC 偏移量格式(±[hh]:[mm]±[hh][mm]±[hh] )。

使用 TimeSpan.Parse 方法:

var time = "+7:30";
time = time.Replace("+", "");  // Remove the + if it is there.
var hours = TimeSpan.Parse(time).TotalHours;