DateTime.Parse抛出格式异常 [英] DateTime.Parse throwing format exception

查看:574
本文介绍了DateTime.Parse抛出格式异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过解析XElement从xml中检索日期和时间字符串. 日期和时间值通过以下方式检索 file.Element("Date").Valuefile.Element("Time").Value.

I retrieve date and time strings from xml by parsing XElement. The date and time values are retrieved by file.Element("Date").Value and file.Element("Time").Value respectively.

检索日期值后,将其解析为DateTime变量

After I retrieve the Date value I parse it to a DateTime variable

DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012

,然后在xaml UI上将此dt值设置为datepicker值

and then this dt value is set to a datepicker value on the xaml UI

datepicker.Value = dt;

我还有一个时间选择器,其值必须由从xml检索的时间值来设置. 要设置时间选择器值,请执行以下操作. 声明3个字符串,例如:

I also have a timepicker whose value have to be set by the Time value retrieved from xml. To set the timepicker value I do the following. declare 3 strings, say:

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'连接起来

I then concatenate the Date Value and string 'b' and 'c'

string total = file.Element("Date").Value + " " + b + c;

total的值现在为'12/29/2012 9:55:00 AM'

the value of total is now '12/29/2012 9:55:00 AM'

然后我尝试将此total字符串解析为DateTime,但是它抛出formatexception

I then try to Parse this total string to a DateTime, but it throws a formatexception

DateTime.Parse(total, CultureInfo.InvariantCulture);

任何帮助表示赞赏...

Any help appreciated...

推荐答案

我已经找到了解决方案. 当尝试以XML格式保存datepicker时,我将timepicker的值另存为XMLElement作为ValueString,因此在转换为字符串时始终会引发错误. 因此,我将其以XML格式保存为Value.ToString(). 现在,它可以正确地从字符串转换为等效的日期或时间了.

I have got the solution for this. When trying to save the datepicker in XML format, I was saving the value of timepicker as XMLElement as ValueString, hence when converted to string always throwed error. So I saved it in XML format as Value.ToString(). Now it can convert correctly from String to Date or Time equivalents.

这篇关于DateTime.Parse抛出格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆