DateTime.Kind和DataRow [英] DateTime.Kind and DataRow
问题描述
当保存到DataRow中时,DateTime类的Kind属性始终设置为DateTimeKind.Unspecified。这是正确的行为吗?有没有办法解决这个问题,那么Kind属性的值将被保留?
以下代码的输出是:
Utc
未指定
DataTable table = new DataTable(" Test");
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType(" System。 DateTime");
column.ColumnName =" testdatetime" ;;
table.Columns.Add(column);
DataRow row;
row = table.NewRow();
DateTime value = DateTime.UtcNow;
row [" testdatetime"] = value;
Console.WriteLine(value.Kind);
Console.WriteLine(((DateTime)row [" ; testdatetime"])。Kind);
您可以通过DataColumn的DateTimeMode属性来控制它。
msdn2.microsoft.com/en-us/library/
system.data.datacolumn。 datetimemode 的。 aspx
默认值是DataSetDateTime.UnspecifiedLocal,它会导致你看到的内容。
我建议:
- 如果你想在UTC时间工作,请使用DataSetDateTime.Utc。
- 否则,使用DataSetDateTime.Unspecified。
有一个讨厌的问题 - 如果您使用Visual Studio DataSet设置它格纳,它将没有任何影响。这是Visual Studio 2008 Beta中修复的错误。解决方法是在运行时在DataColumn上设置DateTimeMode。
还有DataSetDateTime。 Local和DataSetDateTime.UnspecifiedLocal,但恕我直言,如果您跨机器传输DataSet,这些往往会导致.NET自动转换时区。请参阅上面的链接,了解有关其工作原理的详细信息。
the Kind property of the DateTime classes always gets set to DateTimeKind.Unspecified when
saved into a DataRow. Is this correct behavior? is there a way to work a around this so
the value of the Kind property will be retained?
the output from the following code is:
Utc
Unspecified
DataTable table = new DataTable("Test");
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.DateTime");
column.ColumnName = "testdatetime";
table.Columns.Add(column);
DataRow row;
row = table.NewRow();
DateTime value = DateTime.UtcNow;
row["testdatetime"] = value;
Console.WriteLine(value.Kind);
Console.WriteLine(((DateTime)row["testdatetime"]).Kind);
You can control this via the DataColumn's DateTimeMode property.
msdn2.microsoft.com/en-us/library/
system.data.datacolumn.datetimemode.aspx
The default is DataSetDateTime.UnspecifiedLocal, which causes what you are seeing.
I suggest:
-- Use DataSetDateTime.Utc if you want to work in UTC times.
-- Otherwise, use DataSetDateTime.Unspecified.
There is one nasty catch -- if you set this using the Visual Studio DataSet designer, it will have no effect. This is a bug fixed in Visual Studio 2008 Beta. A workaround is to set DateTimeMode on the DataColumn at run time.
There is also DataSetDateTime.Local and DataSetDateTime.UnspecifiedLocal, but IMHO these tend to cause problems due to .NET automatically converting time zones if you transfer the DataSet across machines. See the link above for more details on how this works.
这篇关于DateTime.Kind和DataRow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!