C# DateTime.Parse引发格式异常
我通过解析XElement从xml中检索日期和时间字符串。 日期和时间值由检索C# DateTime.Parse引发格式异常,c#,datetime-format,formatexception,C#,Datetime Format,Formatexception,我通过解析XElement从xml中检索日期和时间字符串。 日期和时间值由检索 file.Element(“日期”).Value分别为和file.Element(“时间”).Value 检索日期值后,我将其解析为DateTime变量 DateTime dt,ts; dt = file.Element("Date").Value; // the value is say 12/29/2012 然后在xaml UI上将此dt值设置为日期选择器值 datepicker.Value = dt; 我还
file.Element(“日期”).Value分别为和file.Element(“时间”).Value
检索日期值后,我将其解析为DateTime变量
DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012
然后在xaml UI上将此dt值设置为日期选择器值
datepicker.Value = dt;
我还有一个时间选择器,其值必须由从xml检索的时间值设置。
要设置时间选择器值,我执行以下操作。
声明3个字符串,例如:
string a = file.Element("Time").Value; // the value is say 9:55 AM
string b = file.Element("Time").Value.Substring(0, 5) + ":00"; // eg 9:55:00
string c = file.Element("Time").Value.Substring(5); // the value is ' AM'
然后将日期值与字符串“b”和“c”连接起来
string total = file.Element("Date").Value + " " + b + c;
total
的值现在为'2012年12月29日上午9:55:00'
然后我尝试将这个total
字符串解析为DateTime,但它抛出了一个formatexception
DateTime.Parse(total, CultureInfo.InvariantCulture);
感谢您的帮助…尝试使用:DateTime.ParseExact
string total = '12/29/2012 9:55:00 AM';
string format = "MM/dd/yyyy H:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
试一试
演示
读取格式字符串详细信息
注意我在小时部分添加了额外的0。它必须是2位数字,否则会出现格式异常。我已经找到了解决方案。
当试图以XML格式保存datepicker时,我将timepicker的值保存为XMLElement作为ValueString,因此当转换为string时总是抛出错误。
所以我以XML格式将其保存为Value.ToString()。
现在它可以正确地从字符串转换为日期或时间等价物。您是否尝试使用CultureInfo.CreateSpecificCulture(“en US”)而不是CultureInfo.InvariantCulture?我假设代码实际上是DateTime.Parse(总计,CultureInfo.InvariantCulture)
notDateTime.Parse(“total,CultureInfo.InvariantCulture”)代码>和帖子中一样?我没有为CultureInfo获取CreateSpecificCulture选项,即使我使用了System.Globalization命名空间。不过我还是尝试了这个DateTime.Parse(“total”,newcultureinfo(“en-US”);它仍然抛出了一个异常错误是的。代码是DateTime.Parse(total,CultureInfo.InvariantCulture);我在小时部分前加了0,但它仍然给我带来了一个错误。@Siddharth查看我的更新答案。另外,请参阅详细信息。是的,我尝试了您提供的格式,但仍然抛出错误。当我将DatePicker值(即DateTime dt=file.Element(“日期”).value)的值分配给计时器选择器时,计时器会取这个值(即timepicker.value=dt),但计时器选择器显示错误的值,即12:00:00 AM(如果DateTime.Parse中只传递了日期,则为默认时间值)。此处有任何解决方法或帮助。
var dateStr = "12/29/2012 09:55:00 AM";
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);