【问题标题】:How to Export/Import DateTime in DataSet C#如何在 DataSet C# 中导出/导入日期时间
【发布时间】:2017-06-11 07:33:19
【问题描述】:

我有两个应用程序,第一个将 DataSet 导出到文件,第二个将该文件读取到 DataSet。两个应用程序都将 CultureInfo 设置为“en-US”,并且 DataSet.Locale 设置为“en-US”。

在第一个应用程序中,我有 DateTime 字段:

dt.Columns.Add("DateCreated", typeof(DateTime));

比写入文件:

ds.WriteXml(fileName);

在第二个应用中:

    ds.ReadXml(reader);

当我尝试从 DataRow 读取 DateTime 字段时:

DateTime? dateCreated = Convert.ToDateTime(dr["DateCreated"]);

抛出异常:

'Convert.ToDateTime(dr["DateCreated"])' 抛出与强制转换相同的“System.FormatException”类型异常,或者当我指定 CultureInfo 时。当我指定使用 Schema 保存 DataSet 时,它也不会转换。

此字段中的日期值格式为:“2017-06-11T08:10:06.2212339 03:00”

为什么会发生这种情况,是否可以在不指定 DateFormat 字符串的情况下将其转换为 DateTime?谢谢!

【问题讨论】:

  • 向我们展示整个方法的代码。还向我们展示发生异常的屏幕截图,以便我们查看其他上下文。
  • 该值看起来不正确 - 它应该有一个 +- 符号,而不是 90 之间的空格(03:00 是与 UTC 的偏移量)
  • 所以它抛出了 FormatException,但消息是什么?在任何情况下,@StephenMuecke 都是正确的,并且该错误会引发 FormatException,并显示“字符串未被识别为有效的 DateTime”。验证简单。
  • 我尝试使用 DataSet 和 DataTable 复制问题,并在 MemoryStream 中写入和读取。效果很好,所以没有运气。
  • 'Convert.ToDateTime(dr["DateCreated"])' 引发了“System.FormatException”类型的异常

标签: c# asp.net asp.net-mvc datetime


【解决方案1】:

如果没有在时区偏移部分使用正号或负号,UTC 日期字符串格式似乎不正确,并且将抛出 FormatException 并带有给定消息 String was not recognized as a valid DateTime

2017-06-11T08:10:06.2212339 03:00
                            ^
                            missing sign offset here

如果DataRow 给出的日期格式固定为正时间偏移,而您只想读取它们,请使用String.Insert 在偏移部分之前插入偏移符号,如下所示:

String date = (dr["DateCreated"] ?? String.Empty).ToString();

if (!String.IsNullOrEmpty(date))
{
    date = date.Insert((date.Length - 5), "+");

    // NB: Convert.ToDateTime will give same value as DateTime.ParseExact here
    DateTime? dateCreated = DateTime.ParseExact(date, "yyyy-MM-ddTHH:mm:ss.FFFFFFF zzzz", 
                            CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}

date & dateCreated 上的输出字符串应该是这样的(基于 UTC):

date: 2017-06-11T08:10:06.2212339 +03:00

dateCreated: 6/11/2017 5:10:06 AM

注意:Convert.ToDateTimeDataRow 输入的情况下可能使用Object 参数而不是string,因此如果dr["DateCreated"] 肯定没有空值,则此代码可能适用:

DateTime? dateCreated = Convert.ToDateTime(dr["DateCreated"].ToString().Insert((date.Length - 6), "+"));

解析示例:.NET Fiddle Demo

相关问题:

Custom DateTime formats when using DataSet.WriteXml in .NET

Reading XML into Datatable gives incorrect DateTime when the time has Time Zone info

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多