我遇到了一些对我来说真的很奇怪的问题,我无法开始理解为什么会这样。
基本上,我正在尝试做一个 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);
现在,当把它作为一个动态值(这是我想要的)时,我在这段代码中得到“String not recognized as a valid DateTime format”:
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; }
}
我真的迷路了。任何人都明白为什么会发生这种情况吗?
编辑
决定提供更多有关如何使用它的信息,因为问题可能来自后面。
我有一个类,我用它来定义属性,使用反射将创建一个数据表。
类有这个属性:
public DateTime last_date { get; set; }
然后我使用这个方法来构建数据表:
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);
}
}
}
最佳答案
你的格式是正确的。
由于您使用 null
作为 IFormatProvider
,我强烈怀疑您的 CurrentCulture
有不同的DateSeparator
比/
或/和不同TimeSeparator
比 :
个字符。
/
和 :
字符在自定义日期和时间解析中是特殊的。它们的意思是:用当前文化日期或时间分隔符替换我
在您的个人资料中,它说您来自葡萄牙语,您当前的文化可能是pt-PT
。并且这种文化有 -
作为 DateSeparator
关于c# - .NET DateTime Parse 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28941168/