我遇到了一些对我来说似乎真的很奇怪的问题,我无法理解为什么会发生这种情况。
基本上,我正在尝试做一个 DateTime.ParseExact ,如果在一个案例上工作而不是在另一个案例上工作。
假设我有这个字符串作为日期字符串:
"11/02/2015 11:59:06:313"
如果我通过给方法提供字符串的显式声明来解析,即下一个代码,一切正常:
DateTime.ParseExact("11/02/2015 11:59:06:313", "dd/MM/yyyy HH:mm:ss:fff", null);
现在,当将其作为动态值(这是我想要的)时,我在以下代码中得到“字符串未被识别为有效的 DateTime 格式”:
DateTime.ParseExact(item.original, "dd/MM/yyyy HH:mm:ss:fff", null);
我也尝试过 Convert.ToDateTime 方法(它抛出了同样的异常):
Convert.ToDateTime(item.original).ToString("dd/MM/yyyy HH:mm:ss:fff");
'item.original' 变量来自一个类(它是该类的字符串属性,定义为
public class XmlData
{
public string tableName { get; set; }
public string columnName { get; set; }
public string original { get; set; }
public int required { get; set; }
public string status { get; set; }
public string type { get; set; }
public string newValue { get; set; }
}
我真的迷路了。为什么会发生这种情况对任何人来说都有意义吗?
编辑
决定提供更多关于如何使用它的信息,因为问题可能来自更远的后面。
我有一个类,我用它来定义属性,使用反射将创建一个 DataTable。
该类具有以下属性:
public DateTime last_date { get; set; }
然后我使用这种方法来构建 DataTable:
public DataTable CreateEmptyDataTable(Type myType)
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in myType.GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
return dt;
}
初始化 DataTable 后,我从 XmlData 类中读取值并使用以下代码将值分配给 last_date 列,如下所示:
//Set the original state
foreach (XmlData item in collection)
{
if (item.tableName == "vehicle")
{
if (item.original == "--NULL--")
dr[item.columnName.Substring(item.tableName.Length + 1)] = DBNull.Value;
else
{
if (item.type == "DT") //DateTime in format "dd/MM/yyyy HH:mm:ss:fff"
dr[item.columnName.Substring(item.tableName.Length + 1)] = DateTime.ParseExact(item.original, "dd/MM/yyyy HH:mm:ss:FFF", null);
else
dr[item.columnName.Substring(item.tableName.Length + 1)] = Convert.ChangeType(item.original, dt.Columns[item.columnName.Substring(item.tableName.Length + 1)].DataType);
}
}
}