我有一个数据网格,它使用DateTime列进行排序,该列来自转换为本地时间的UTC值。问题在于夏令时,因为一年中有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年6月11日上午6:30
当地日期:11/06/2016 1:30 AM
UTC From Local:11/06/2016 7:30
正如您可以看到列" UTC From Local"是错的或至少我期望6:30(考虑夏令时)而不是7:30(没有夏令时)。
任何帮助?????
答案 0 :(得分:0)
您必须牢记DataColumn的DateTimeMode属性。如果您创建新的DataColumn
,则会将其设置为未指定。但在您的用例中,您需要 Utc 和本地
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();
答案 1 :(得分:-1)
也许您可以尝试获取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();