日期时间转换出现格式异常

5
我通过解析XElement从xml中检索日期和时间字符串。日期和时间值分别通过file.Element("Date").Valuefile.Element("Time").Value检索。
在检索到日期值后,我将其解析为DateTime变量。
DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012

然后将此“dt”值设置为XAML UI上的日期选择器值。
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,但它抛出了一个格式异常

DateTime.Parse(total, CultureInfo.InvariantCulture);

任何帮助都将不胜感激...

你尝试使用CultureInfo.CreateSpecificCulture("en-US")而不是CultureInfo.InvariantCulture了吗? - András Ottó
3
我假设代码实际上是 DateTime.Parse(total, CultureInfo.InvariantCulture); 而不是帖子中的 DateTime.Parse("total, CultureInfo.InvariantCulture");,对吗? - mlorbetske
尽管我已经使用了System.Globalization命名空间,但我仍然无法获得CultureInfo的CreateSpecificCulture选项。 不过,我尝试了DateTime.Parse("total", new CultureInfo("en-US")); 它仍然抛出了FormatException错误。 - Siddharth
是的。代码是 DateTime.Parse(total, CultureInfo.InvariantCulture); - Siddharth
3个回答

8
尝试使用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# DateTime Format获取格式字符串的详细信息。

注意,我给小时部分添加了额外的0。必须为2位数字,否则将出现格式异常。


我在小时部分前面添加了0,但仍然出现错误。 - Siddharth

0

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

@Siddharth,请查看我的更新答案。此外,请参考http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx获取详细信息。 - Kapil Khandelwal
是的,我已经尝试了您给出的格式,但仍然出现错误。 - Siddharth
当我将DatePicker的值赋给TimePicker时,即DateTime dt = file.Element("Date").Value,TimePicker会接受这个值,即timepicker.Value = dt。但是,TimePicker显示错误的值,即12:00:00 AM(如果仅传递日期,则为默认时间值DateTime.Parse)。有什么解决方法或帮助吗? - Siddharth

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接