我遇到了将DateTime对象存储到数据表中的问题,它丢失了设置到它的Kind信息.例如,如果DateTime.Kind是UTC,一旦我将它分配给datarow值,它就会将Kind更改为Unspecified.Please找到下面的代码.
public class LocalTimeToUtcConverter { public DateTime Convert(DateTime localDate) { var utcOffset = TimeZoneInfo.Local.GetUtcOffset(localDate); var utc = localDate.ToUniversalTime(); return utc + utcOffset; } } [Test] public void Should_set_datetime_column_kind_to_utc() { var localDate = new DateTime(2010, 11, 01, 00, 00, 00); Assert.That(localDate.Kind == DateTimeKind.Unspecified); var converter = new LocalTimeToUtcConverter(); DateTime date = converter.Convert(localDate); Assert.That(localDate.Kind == DateTimeKind.Utc); var data = CreateTable(date); //Failes-Why???? Assert.That(((DateTime)data.Rows[0].ItemArray[0]).Kind == DateTimeKind.Utc); } private DataTable CreateTable(DateTime date) { DataTable table = new DataTable(); table.Columns.Add(new DataColumn("Date1", typeof(DateTime))); for (int i = 0; i < 10; i++) { var newRow = table.NewRow(); newRow[0] = date; table.Rows.Add(newRow); } return table; }
请你告诉我一个解决方法吗?
谢谢!!!
table.Columns.Add(new DataColumn("Date1",typeof(DateTime)));
使用DataColumn.DateTimeMode属性:
var col = new DataColumn("Date1", typeof(DateTime)); col.DateTimeMode = DataSetDateTime.Utc; table.Columns.Add(col);
如果您将数据库中的日期存储在UTC中,则无关紧要.