Date and time conversion in C# - DateTime.ParseExact() not working as expected
.net, c#, datetime
Solution
You could fix your date:
var parts = "1-Mar-13 92230".Split(' ');
if (parts[1].Length == 5)
{
parts[1] = "0" + parts[1];
}
var newDate = parts[0] + " " + parts[1];
var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss", System.Globalization.CultureInfo.CurrentCulture);
Problem
I have date/time format, for example: "1-Mar-13 92230" According to this document and this link the format is as follows: "d-MMM-yy Hmmss", because: ``` Day is single digit, 1-30 Month is 3 letter abbreviation, Jan/Mar etc. Year is 2 digits, eg 12/13 Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09) Minute is standard (eg 01, 52) Second is standard (eg 30, 02) ``` I'm trying to run the following code in my program, but I keep getting an error of "String was not recognized as a valid DateTime." ``` string input = "1-Mar-13 92330"; var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss", System.Globalization.CultureInfo.CurrentCulture); ``` Please help, I'm not too familiar with DateTime conversions, but I can't see where I've gone wrong here. Thanks! UPDATE: Is this because time cannot be parsed without colons in between? (eg 1-Mar-13 9:22:30 gets parsed, but i have an external data source that would be impossible to rewrite from Hmmss to H:mm:ss)