c# - 当服务器设置为 UTC 时创建夏令时感知日期时间

标签 c# datetime azure utc dst

我的应用程序托管在 Windows Azure 上,所有服务器都设置为 UTC。

我需要知道任何给定的 DateTime 何时适用夏令时。为简单起见,我们可以假设我的用户都在英国(因此使用格林威治标准时间)。

我用来转换 DateTime 对象的代码是

public static DateTime UtcToUserTimeZone(DateTime dateTime)
{
    dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

    var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Greenwich Standard Time");

    var userDateTime = TimeZoneInfo.ConvertTime(dateTime, timeZone);

    return DateTime.SpecifyKind(userDateTime, DateTimeKind.Local);
}

但是,以下测试在最后一行失败;转换后的 DateTime 不知道它应该是夏令时。

[Test]
public void UtcToUserTimeZoneShouldWork()
{
    var utcDateTime = new DateTime(2014, 6, 1, 12, 0, 0, DateTimeKind.Utc);
    Assert.IsFalse(utcDateTime.IsDaylightSavingTime());

    var dateTime = Utils.UtcToUserTimeZone(utcDateTime);
    Assert.IsTrue(dateTime.IsDaylightSavingTime());
}

请注意,只有当我的 Windows 时区设置为(UTC) 协调世界时时,此操作才会失败。当设置为(UTC)都柏林、爱丁堡、里斯本、伦敦(或任何其他遵守夏令时的北半球时区)时,测试通过。如果您在 Windows 中更改此设置,则需要重新启动 Visual Studio 才能使更改完全生效。

我错过了什么?

最佳答案

您的最后一行指定该值位于其运行的系统的本地时区 - 但实际上并非如此......它是使用不同的时区进行转换的。

基本上DateTimesomewhat broken ,在我看来 - 这使得它很难正确使用。无法说“此 DateTime 值位于时区 x” - 您可以执行转换来查找特定的本地时间,但不会记住时区。

例如,来自 DateTime.IsDaylightSavingTime 的文档(强调我的):

This method determines whether the current DateTime value falls within the daylight saving time range of the local time zone, which is returned by the TimeZoneInfo.Local property.

显然我有偏见,但我建议使用我的 Noda Time为此项目 - 很可能使用 ZonedDateTime 。您可以调用GetZoneInterval获得 ZoneInterval对于该 ZonedDateTime,然后使用 ZoneInterval.Savings检查当前偏移量是否包含夏令时部分:

bool daylight = zonedDateTime.GetZoneInterval().Savings != Offset.Zero;

这有点啰嗦...我添加了一个feature request考虑向 ZonedDateTime 添加一个 IsDaylightSavingTime() 方法...

关于c# - 当服务器设置为 UTC 时创建夏令时感知日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945637/

相关文章:

c# - 如何使用 Selenium 将样式属性设置为元素?

c# - 如何转换 DateTime[] 日期 = datelist.ToArray();在 C# 中仅显示日期

azure - 在 Azure DocumentDB 中,如何获取集合中所有属性的列表?

c# - 使用不同的界面使用 Web 服务

c# - 如何插入带有 1 :n relationship in Azure App Service 的实体

ruby-on-rails - 在 Rails 中使用 DateTime 解析自定义 DATE_FORMAT

javascript - Date.toISOString() 但本地时间而不是 UTC

azure - 无法创建azure sql server的可能原因?

sql-server - 包含多个参数的存储过程where语句

c# - 无法从代码隐藏访问控制