tags:

views:

263

answers:

5

Been trying to solve this one for hours...

string date = "2009-09-23T13:00:00"

DateTime t = new 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."

+13  A: 
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");
David Stratton
+4  A: 

You'll have to specify the whole string from which it is parsed.

DateTime.ParseExact(date, "yyyy-MM-ddTHH:mm:ss", null);
Bobby
ParseExact returns a DateTime or throws an exception (no boolean return). The TryParse methods return booleans.
Sean Carpenter
ParseExact doesn't return a bool, it returns a DateTime...
Webleeuw
@Sean, Webleeuw: Oh yeah, right...got those two mixed up, sorry.
Bobby
+1  A: 

ParseExact requires the string to exactly match the format. This one doesn't. You need yyyy-MM-ddTHH:mm:ss as your string.

David M
+2  A: 

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.

Sebastian Dietz
+4  A: 

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.

Greg Beech
XmlConvert was the answer I was looking for (otherwise I'd have added it ;-p)
Marc Gravell