DateTime.解析抛出格式异常

本文关键字:格式 异常 DateTime | 更新日期: 2023-09-27 17:50:00

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

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

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

,然后这个dt值被设置为xaml UI上的一个日期拾取器值

datepicker.Value = dt;

我还有一个时间选择器,其值必须通过从xml检索到的Time值来设置。要设置时间选择器的值,我执行以下操作。声明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的值现在是'12/29/2012 9:55:00 AM'

然后我尝试解析这个total字符串到一个日期时间,但它抛出一个格式异常

DateTime.Parse(total, CultureInfo.InvariantCulture);

DateTime.解析抛出格式异常

尝试DateTime。ParseExact

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);

演示。

阅读c#日期时间格式的格式字符串的详细信息。

注意我在小时部分添加了额外的0。必须是2位数字,否则会导致格式异常。

尝试使用: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);

我已经得到了解决方案。当尝试以XML格式保存日期选择器时,我将时间选择器的值保存为XMLElement作为ValueString,因此当转换为字符串时总是抛出错误。因此,我将其保存为XML格式的Value.ToString()。现在,它可以正确地从字符串转换为日期或时间等效。