【问题标题】:Convert UTC Time to local Time using time zone info from database使用数据库中的时区信息将 UTC 时间转换为本地时间
【发布时间】:2017-05-12 17:57:52
【问题描述】:

我有来自数据库的特定记录的时区信息,例如 -6,这意味着 UTC-6
如何使用这个 -6 将我的 UTC 时间转换为 UTC-6

我想我必须在 c# 中使用 TimeZoneInfo。
并非所有记录的时区信息都相同。

【问题讨论】:

  • 是的,对不起,我被标题弄糊涂了

标签: c# datetime utc


【解决方案1】:

您可以使用 DateTimeOffset 创建具有偏移量的日期。

var dbDate = myRawDbDate.Kind == DateTimeKind.Unknown ? DateTime.SpecifyKind(myRawDbDate, DateTimeKind.Utc): myRawDbDate;
var localDdate = new DateTimeOffset(dbDate, new TimeSpan(0,6,0)).DateTime;

【讨论】:

  • 日期仍未转换为 UTC-6 .. DateTime.SpecifyKind(myRawDbDate, DateTimeKind.Utc) 这将返回 UTC 本地日期时间。
  • 小语法错误:.DateTime 前缺少右括号,TimeSpan 大写。你也可以使用更易读的(无论如何对我来说)TimeSpan.FromHours(6)
【解决方案2】:

您好,您可以使用 TimeZoneInfo 类。

 var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); //UTC-6
 var UTC6date = TimeZoneInfo.ConvertTimeFromUtc(Yourdate.ToUniversalTime(), timeZone);

更多信息在这里是链接。 MSDN:https://msdn.microsoft.com/en-us/library/bb382835(v=vs.110).aspx

查看 UTC-6:00 等的所有时区。

使用TimeZoneInfo.GetSystemTimeZones() 方法。

示例代码:

var timeZonList = TimeZoneInfo.GetSystemTimeZones();

    foreach (var item in timeZonList)
    {
        Console.WriteLine(item);
    }

TimeZoneInfo.ConvertTimeFromUtc(date converted to universal time, "Timezone to convert your date").

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-05-31
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2018-07-27
    • 2014-10-05
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多