DateTime.Parse throwing format exception

走远了吗. 提交于 2019-12-01 17:48:27

问题


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.

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

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

datepicker.Value = dt;

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'

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

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

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

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

DateTime.Parse(total, CultureInfo.InvariantCulture);

Any help appreciated...


回答1:


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

Demo here.

Read C# DateTime Format for format string detail.

Note that i have added extra 0 to hour part. It must be 2 digits otherwise format exception will occur.




回答2:


Try using: 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);



回答3:


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.



来源:https://stackoverflow.com/questions/14079663/datetime-parse-throwing-format-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!