【问题标题】:C# Convert DateTime to GMT or BST from UTCC# 将 DateTime 从 UTC 转换为 GMT 或 BST
【发布时间】:2020-12-14 08:28:20
【问题描述】:

我在 SQL 中存储了一个日期时间,该日期时间是从 UTC 格式的 Azure 服务器中检索到的。

当我从 SQL 中检索此日期时间时,日期时间类型未指定...

在英国,我们目前处于 BST,如何根据一年中的时间将我从 SQL 收到的日期时间转换为 BST 或 GMT?

我的测试/生产服务器在 Azure 中,在 UTC 上运行。

回答

感谢@jonathon,我想出了以下扩展方法来解决我的问题。

      public static DateTime CovertDateTimeToDateTimeGmt(this DateTime source)
    {
        var sourceUtc = DateTime.SpecifyKind(source, DateTimeKind.Utc);
        var destinationTimezoneId = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
        var sourceLocalTime = TimeZoneInfo.ConvertTimeFromUtc(sourceUtc, destinationTimezoneId);
        return sourceLocalTime;
    }

因为我从 SQL 收到的日期时间没有指定日期时间类型,所以我首先将其转换为指定类型的新日期时间。

【问题讨论】:

    标签: c# datetime utc gmt


    【解决方案1】:

    使用ConvertTimeFromUtc 并指定要转换成的时区。必要时应考虑夏令时。

    TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
    DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
    

    见: https://docs.microsoft.com/en-us/dotnet/api/system.timezoneinfo.converttimefromutc?view=netcore-3.1

    https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones

    【讨论】:

    • 即使我收到的值不包含指定类型的 UTC,这项工作是否有效。一旦日期时间值存储在 SQL 中,系统就不知道它的种类是 UTC。
    • 当您检查DateTime 值时,它的Kind 是什么?文档说 ConvertTimeFromUtc 必须是“未指定”或“UTC”才能正常运行
    • 如果kind 不是“未指定”或“UTC”,则必须使用DateTime.SpecifyKind() 进行转换
    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2011-10-20
    • 2019-11-29
    • 2014-09-04
    • 2010-12-06
    • 2018-09-17
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多