Sid*_*rth 5 c# datetime-format formatexception
我通过解析XElement从xml中检索日期和时间字符串.日期和时间值分别由file.Element("Date").Value和检索
file.Element("Time").Value.
检索Date值后,我将其解析为DateTime变量
DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012
Run Code Online (Sandbox Code Playgroud)
然后将此dt值设置为xaml UI上的datepicker值
datepicker.Value = dt;
Run Code Online (Sandbox Code Playgroud)
我还有一个timepicker,其值必须由从xml检索的Time值设置.要设置timepicker值,请执行以下操作.声明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'
Run Code Online (Sandbox Code Playgroud)
然后我连接日期值和字符串'b'和'c'
string total = file.Element("Date").Value + " " + b + c;
Run Code Online (Sandbox Code Playgroud)
价值total现在是'12/29/2012 9:55:00 AM'
然后我尝试将此total字符串解析为DateTime,但它会抛出一个formatexception
DateTime.Parse(total, CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏...
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);
Run Code Online (Sandbox Code Playgroud)
在这里演示.
读取格式字符串详细信息的C#DateTime格式.
请注意,我已添加额外的0到小时部分.它必须是2位数,否则将发生格式异常.
我已经找到了解决方案。当尝试以 XML 格式保存日期选择器时,我将时间选择器的值保存为 XMLElement 作为 ValueString,因此在转换为字符串时总是会抛出错误。所以我将其保存为 XML 格式:Value.ToString()。现在它可以正确地从字符串转换为日期或时间等效项。