DateTimeOffset不明确的示例

本文关键字:不明确 DateTimeOffset | 更新日期: 2023-09-27 18:30:12

我们在数据库/模型中有DateTimeOffsets。为了在Web中显示这些值,我们将DateTimeOffsets转换为当前用户的时区。

根据MSDN的说法,DateTimeOffset在特定时区中可能不明确:

TimeZoneInfo.Is模糊时间方法(DateTimeOffset)

这对我来说毫无意义。有人能给我一个模糊的DateTimeOffset示例吗
我们在"西欧标准时间"时区。

DateTimeOffset不明确的示例

我认为混淆来自于这里定义"歧义"的方式。

需要明确的是,DateTimeOffset对自己来说从来都不是模棱两可的。它总是表示绝对瞬时时间中的特定时刻。给定日期、时间和偏移量,我可以告诉您当地的墙时间和精确的UTC时间(通过应用偏移量)。

但是,该值的墙时间部分在特定时区内可能不明确。也就是说,当您忽略偏移时,日期和时间仅TimeZoneInfo.IsAmbiguousTime就是这么告诉你的。如果不是偏移量,则该值将不明确。墙时间可能会让处于该时区的人感到困惑。

考虑这个方法有两个重载,一个重载DateTime,一个过载DateTimeOffset

  • 当CCD_ 6是CCD_ 7时,CCD_。

    DateTime dt = new DateTime(2016, 10, 30, 2, 0, 0);
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
    bool ambiguous = tz.IsAmbiguousTime(dt);  // true
    
  • 它对其他类型来说意义不大,因为它首先转换到给定的时区,但它仍然做同样的事情:

    DateTime dt = new DateTime(2016, 10, 30, 1, 0, 0, DateTimeKind.Utc);
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
    bool ambiguous = tz.IsAmbiguousTime(dt);  // true
    
  • DateTimeOffset重载的作用与前面的示例基本相同。无论偏移量是多少,它都会应用于日期和时间,然后仅在生成的日期和时间上检查模糊性——就像第一个例子中一样。

    DateTimeOffset dto = new DateTimeOffset(2016, 10, 30, 2, 0, 0, TimeSpan.FromHours(1));
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
    bool ambiguous = tz.IsAmbiguousTime(dto);  // true
    
  • 即使有一个对该时区没有意义的偏移,它仍然会在比较之前应用。

    DateTimeOffset dto = new DateTimeOffset(2016, 10, 29, 19, 0, 0, TimeSpan.FromHours(-5));
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
    bool ambiguous = tz.IsAmbiguousTime(dto);  // true
    

它可以归结为过载的实现,本质上是:

// Make sure the dto is adjusted to the tz.  This could be a no-op if it already is.
DateTimeOffset adjusted = TimeZoneInfo.ConvertTime(dto, tz);
// Then just get the wall time, stripping away the offset.
// The resulting datetime has unspecified kind.
DateTime dt = adjusted.DateTime;
// Finally, call the datetime version of the function
bool ambiguous = tz.IsAmbiguousTime(dt);

你可以在这里的.net参考源中看到这一点。他们将其压缩为两行,并在DST不适用时为其提供一条快捷方式,以获得更好的性能,但这就是它的作用。

文档中所说的内容是否不清楚?

通常,当时钟设置为从夏令时返回到标准时间时,会导致时间不明确

也就是说,如果你在凌晨2点结束夏令时,并将时钟重置为凌晨1点,那么如果有人在凌晨1点30分左右开始说话,你不知道这是30分钟后的事还是过去的事。

有一组值(通常为一小时)映射到UTC时间的两组不同时刻。

样本是(去年10月的周日2:00-3:00)

DateTimeOffset example = new DateTimeOffset(2015, 10, 25, 2, 30, 0, 
  new TimeSpan(0, 2, 0, 0));
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
if (tst.IsAmbiguousTime(example))
  Console.Write("Ambiguous time");

不明确的时间相反的是无效的

TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
if (tst.IsInvalidTime(new DateTime(2016, 03, 27, 2, 30, 0)))
  Console.Write("Invalid time");