如何坚持的DateTime类,同时存储DateTime对象到数据表? [英] How to persist DateTime Kind while storing a datetime object into a data table?
问题描述
我面临着存储DateTime对象到DataTable的问题,它失去套入it.For例如类信息,如果该DateTime.Kind是UTC,一旦我把它分配给数据行的价值它改变了善待Unspecified.Please找到下面的代码。
公共类LocalTimeToUtcConverter
{
公众的DateTime转换(日期时间LOCALDATE )
{
VAR UTCOFFSET = TimeZoneInfo.Local.GetUtcOffset(LOCALDATE);
VAR UTC = localDate.ToUniversalTime();
返回UTC + UTCOFFSET;
}
}
[测试]
公共无效Should_set_datetime_column_kind_to_utc()
{
变种LOCALDATE =新的日期时间(2010,11,01 ,00,00,00);
Assert.That(localDate.Kind == DateTimeKind.Unspecified);
变种器=新LocalTimeToUtcConverter();
日期时间日期= converter.Convert(LOCALDATE);
Assert.That(localDate.Kind == DateTimeKind.Utc);
VAR数据= CREATETABLE(日期);
// Failes,为什么????
Assert.That(((日期时间)data.Rows [0] .ItemArray [0])种类== DateTimeKind.Utc);
}
私人数据表CREATETABLE(DateTime的日期)
{
DataTable的表=新的DataTable();
table.Columns.Add(新的DataColumn(日期1的typeof(DateTime的)));
的for(int i = 0;我小于10;我++)
{
VAR NEWROW = table.NewRow();
NEWROW [0] =日期;
table.Rows.Add(NEWROW);
}
返回表;
}
请你能告诉我这是一个解决办法?
谢谢!
table.Columns.Add (新的DataColumn(日期1的typeof(DateTime的)));
块引用>
使用的DataColumn.DateTimeMode属性:
VAR山坳=新的DataColumn(日期1的typeof(DateTime的));
col.DateTimeMode = DataSetDateTime.Utc;
table.Columns.Add(COL);
如果您存储在您的UTC日期质数据库,应该像你这不应该的问题。
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?
Thanks!!!
解决方案table.Columns.Add(new DataColumn("Date1", typeof(DateTime)));
Use the DataColumn.DateTimeMode property:
var col = new DataColumn("Date1", typeof(DateTime)); col.DateTimeMode = DataSetDateTime.Utc; table.Columns.Add(col);
This shouldn't matter if you store dates in your dbase in UTC, like you should.
这篇关于如何坚持的DateTime类,同时存储DateTime对象到数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!