【发布时间】:2018-10-18 01:04:43
【问题描述】:
对于即时日期时间跟踪,我使用DateTimeOffset 数据类型。以下函数将用户对应的TimeZone ID偏移量添加到DateTimeOffset的UTC DateTime属性中
根据documentation,UtcDateTime 将对DateTimeOffset 执行时区转换和类型转换。以下代码没有。为什么没有发生转换?
添加TimeSpan偏移的函数,
public static DateTimeOffset GetUtcDateTime (DateTime sourceDateTime, string timeZoneId) {
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById (timeZoneId);
TimeSpan offset = timeZone.GetUtcOffset (sourceDateTime);
DateTimeOffset utcTime = new DateTimeOffset (sourceDateTime, offset);
return utcTime;
}
在这里我尝试转换,
DateTimeOffset utcDate = (DateTime.UtcNow);
DateTime fromUtc = utcDate.DateTime;
DateTimeOffset UtcDate = StaticHandlers.GetUtcDateTime (fromUtc, "America/Los_Angeles");
Console.WriteLine ("UTC now is {0} and UTC Date LA is {1} and UtcDateTime LA is {2}", utcDate, UtcDate, utcDate.UtcDateTime);
输出是,
UTC 现在是 2018 年 5 月 8 日上午 6:43:37 +00:00,UTC 日期洛杉矶是 5/8/18 6:43:37 AM -07:00 UtcDateTime LA 是 5/8/18 6:43:37 AM
更新,
我想保留 UTC 和用户偏移量以用于跟踪目的。 DST 在这种情况下很重要。下面的例子说明了我在说什么。
DateTime currentDateTime = DateTime.Now;
DateTime beforeDST_LA = new DateTime (2018, 3, 11, 0, 0, 0);
DateTime afterDST_LA = new DateTime (2018, 3, 12, 0, 0, 0);
TimeSpan offsetCurrent = tzi.GetUtcOffset (currentDateTime);
TimeSpan offsetBeforeDST = tzi.GetUtcOffset (beforeDST_LA);
TimeSpan offsetAfterDST = tzi.GetUtcOffset (afterDST_LA);
Console.WriteLine ("Current offset is {0} before DST is {1} and After DST is {2}", offsetCurrent, offsetBeforeDST, offsetAfterDST);
在 DST 为 -08:00:00 之前和 DST 之后的当前偏移量为 -07:00:00 -07:00:00
【问题讨论】:
-
输出看起来正确。 2018 年 5 月 8 日上午 6:43:37 UTC 在任何地方都是 2018 年 5 月 8 日上午 6:43:37 UTC,即使在洛杉矶也是如此。当然,本地时区会与 UTC 有偏差
-
所以输出的
UtcDateTime LA部分不应该回到 7 小时? -
正确。 UTC 的历史基准是伦敦时间(没有夏令时)。所以在世界各地都是一样的。它从来没有时区问题,因为它完全忽略了它们。这就是我们喜欢 IT 的原因 ;-)。只有当地时间有偏移量。
-
所以基本上我在这里做的是错误的,我应该将 DateTime.Now 与偏移量一起存储吗?
-
那我这里怎么转换呢?我的意思是在上面的例子中显示落后 7 小时的时间?
标签: c# .net datetime timezone datetimeoffset