Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime Parse dilemma in C#

Tags:

c#

datetime

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

like image 222
Joao Heleno Avatar asked Feb 25 '26 00:02

Joao Heleno


2 Answers

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");
like image 151
David Avatar answered Feb 27 '26 12:02

David


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.

like image 33
Greg Beech Avatar answered Feb 27 '26 14:02

Greg Beech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!