DateTime Parse dilemma in C#
Been trying to solve this one for hours...
string date = "2009-09-23T13:00:00"
DateTime t = n开发者_高级运维ew DateTime();
t = DateTime.ParseExact(date, "HH:mm", null);
Results in this exception:
System.FormatException was unhandled Message="String was not recognized as a valid DateTime."
t = DateTime.ParseExact(date, "yyyy-MM-ddTHH:mm:ss", null);
With ParseExact, you're trying to take a string and tell the parser exactly what format the string is in. The above line will convert this to a valid DateTime.
If you want to SHOW only the hours and minutes, you would then add the following:
string myString = t.ToString("HH:mm");
You're trying to specify a format that does not match the input. ParseExact
requires you to specify the input format; you cannot simply specify a format indicating which components you would like to extract.
The format you would need to use here is "yyyy-MM-ddTHH:mm:ss"
.
However, given that this looks like an XML date/time format, if it is then you may be better off using the XmlConvert.ToDateTime
method instead as it can handle the subtleties of the XML date format specification.
You'll have to specify the whole string from which it is parsed.
DateTime.ParseExact(date, "yyyy-MM-ddTHH:mm:ss", null);
The documentation says it all:
The format of the string representation must match a specified format exactly or an exception is thrown.
Your date string does not match the format HH:mm.
By the way, you can leave the = new DateTime(); part away.
ParseExact requires the string to exactly match the format. This one doesn't. You need yyyy-MM-ddTHH:mm:ss as your string.
精彩评论