LocalTime 到 UTC 保持 DST

LocalTime to UTC keeping DST

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

        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 日期:11/06/2016 6:30 AM

本地日期:11/06/2016 1:30 AM

UTC 来自本地:11/06/2016 7:30 AM

如您所见,"UTC From Local" 列是错误的,或者至少我希望 6:30(考虑夏令时)而不是 7:30(不考虑夏令时)。

有帮助吗?????

也许您可以尝试获取 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();

你要记住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();