如何分析时区偏移量字符串
本文关键字:偏移量 字符串 时区 | 更新日期: 2023-09-27 18:33:18
我从我的数据库中检索一个时区偏移量的值。我得到的价值是及时的。
例如,它可以是"-5:00"
、"+7:30"
、"+3:00"
等。
如何将其转换为双精度,以便我可以对DateTime
对象进行AddHours()
调用?
约翰·科尔纳的回答有几个缺点;
- 根据
+
或-
,可能需要额外的字符串操作。它可以处理-
符号或没有符号,但不能处理+
字符本身。 - 由于他使用的
TimeSpan.Parse(string)
过载,如果CurrentCulture
的TimeSeparator
不是:
(我知道这很少见),这种方法会抛出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;