Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

c# - DateTime.Parse throwing format exception

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...