我在将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;
}
请您告诉我解决方法吗?
谢谢!!!
最佳答案
使用DataColumn.DateTimeMode属性:
var col = new DataColumn("Date1", typeof(DateTime));
col.DateTimeMode = DataSetDateTime.Utc;
table.Columns.Add(col);
是否像您一样将日期存储在UTC的dbase中也没关系。
关于c# - 将datetime对象存储到数据表中时,如何持久化DateTime Kind?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3990809/