【问题标题】:LocalTime to UTC keeping DSTLocalTime 到 UTC 保持 DST
【发布时间】:2017-04-09 10:50:19
【问题描述】:

我有一个使用 DateTime 列排序的数据网格,该列来自转换为本地时间的 UTC 值。问题在于 DST,因为一年中有 1 个小时会重复(从 11 月 6 日凌晨 2:00:00 回到凌晨 1:00:00)。我已经实现了一种使用从 IComparable 继承的类来比较列的方法,并手动比较使用 ToUniversalTime() 再次转换它们的日期,但它返回错误的值。为了更好地解释,让我举个例子:

        DataTable table = new DataTable();
        table.Columns.Add("UTC Date", typeof(DateTime));
        table.Columns.Add("Local Date", typeof(DateTime));            
        table.Columns.Add("UTC From Local", typeof(DateTime));
        dataGridView1.DataSource = table;
        DateTime aux;

        DataRow newRow = table.NewRow();
        aux = new DateTime(2016, 11, 06, 06, 30, 0, DateTimeKind.Utc);
        newRow["UTC Date"] = aux;
        newRow["Local Date"] = aux.ToLocalTime();
        newRow["UTC From Local"] = Convert.ToDateTime(newRow["Local Date"]).ToUniversalTime(); table.Rows.Add(newRow);

显示的值将是:

UTC 日期:2016 年 11 月 6 日上午 6:30

本地日期:2016 年 11 月 6 日上午 1:30

UTC 本地时间:2016 年 11 月 6 日上午 7:30

如您所见,“UTC From Local”列是错误的,或者至少我预计 6:30(考虑 DST)而不是 7:30(没有 DST)。

有什么帮助吗??????

【问题讨论】:

    标签: c# date datetime utc dst


    【解决方案1】:

    您必须牢记 DataColumn 的 DateTimeMode 属性。如果您创建一个新的DataColumn,它会设置为Unspecified。但在您的用例中,您需要 UtcLocal

    var table = new DataTable();
    table.Columns.Add("UTC Date", typeof(DateTime)).DateTimeMode = DataSetDateTime.Utc;
    table.Columns.Add("Local Date", typeof(DateTime)).DateTimeMode = DataSetDateTime.Local;
    table.Columns.Add("UTC From Local", typeof(DateTime)).DateTimeMode = DataSetDateTime.Utc;
    
    var newRow = table.NewRow();
    var aux = new DateTime(2016, 11, 06, 06, 30, 0, DateTimeKind.Utc);
    newRow["UTC Date"] = aux;
    newRow["Local Date"] = aux.ToLocalTime();
    newRow["UTC From Local"] = Convert.ToDateTime(newRow["Local Date"]).ToUniversalTime();
    

    【讨论】:

    • 非常感谢!它奏效了,让我尝试将这个解决方案应用于真正的应用程序,因为我发布的只是一个例子。所以通过阅读您的解决方案,我可以假设使用 ToLocalTime() 不会丢失 DST 信息,问题是在创建 DataTable 时我没有指定 DateTimeMode
    【解决方案2】:

    也许您可以尝试获取 GTM 偏移并将其添加到您的“UTC From Local”:

    aux = new DateTime(2016, 11, 06, 06, 30, 0, DateTimeKind.Utc);
    newRow["UTC Date"] = aux;
    newRow["Local Date"] = aux.ToLocalTime();
    TimeSpan UtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(aux);
    newRow["UTC From Local"] = Convert.ToDateTime(newRow["Local Date"].Add(UtcOffset)).ToUniversalTime();
    

    【讨论】:

    • 我不明白。您在 UTC 上拨打 GetUtcOffset 吗?你期待什么?
    • 我猜在 UTC 上调用 GetUtcOffset 会得到 0,无论如何,从 DST 中的日期得到的也与 DST 中的日期相同的偏移量。我相信唯一的区别是打电话给IsDaylightSavingTime()
    猜你喜欢
    • 1970-01-01
    • 2016-12-16
    • 2012-11-30
    • 2011-10-11
    • 2011-09-24
    • 2016-11-01
    • 2020-02-25
    • 2013-09-25
    • 2022-06-16
    相关资源
    最近更新 更多