本文介绍了如何在将日期时间对象存储到数据表中时保留 DateTime Kind?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在将 DateTime 对象存储到数据表时遇到问题,它会丢失设置到其中的 Kind 信息.例如,如果 DateTime.Kind 是 UTC,一旦我将其分配给数据行值,它会将 Kind 更改为未指定.请在下面找到代码.
I’m facing an issue with storing the DateTime object into a datatable, it looses the Kind information set into it.For example if the DateTime.Kind is UTC, once I assign it to the datarow value it changes the Kind to Unspecified.Please find the code below.
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;
}
请问您能告诉我一个解决方法吗?
Please can you tell me a workaround for this?
谢谢!!!
推荐答案
使用 DataColumn.DateTimeMode 属性:
Use the DataColumn.DateTimeMode property:
var col = new DataColumn("Date1", typeof(DateTime));
col.DateTimeMode = DataSetDateTime.Utc;
table.Columns.Add(col);
如果您将日期以 UTC 格式存储在 dbase 中,这应该无关紧要.
This shouldn't matter if you store dates in your dbase in UTC, like you should.
这篇关于如何在将日期时间对象存储到数据表中时保留 DateTime Kind?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!