Search code examples
c#string-parsing

Parse date time from string of format ddMMMyyyy hhmm (with Month-Name)


I am kind of stuck with an issue where I am unable to to parse the date and time from a string, which I am reading from a text file. The string I am getting is in following format:

05SEP1998 2400

and I am trying to parse the string through the following code:

string dateTimeStr = "05SEP1998 2400"

var provider = CultureInfo.InvariantCulture;

const string Format = "ddMMMyyyy hhmm";

var dateTime = DateTime.ParseExact(dateTimeStr, Format, provider);

But while parsing, the above code throws a FormatException:

String was not recognized as a valid DateTime.

Could anybody please help me fixing this issue?


Solution

  • hh is 12 hour, HH is 24 hour. However, it must be in the range 0-23, not 24. If you can't easily change how those date strings are generated, you can parse it manually:

    string dateTimeStr = "05SEP1998 2400";
    
    var provider = CultureInfo.InvariantCulture;
    
    const string Format = "ddMMMyyyy HHmm";
    int HourPos = Format.IndexOf("HH");
    var hour = dateTimeStr.Substring(HourPos, 2);
    bool addDay = hour == "24";
    if (addDay)
        dateTimeStr = dateTimeStr.Substring(0, HourPos) + "00" + dateTimeStr.Substring(HourPos + 2);
    var dateTime = DateTime.ParseExact(dateTimeStr, Format, provider);
    if (addDay)
        dateTime += TimeSpan.FromHours(24);
    

    Note that this will throw exceptions if dateTimeStr doesn't have the right number of characters. You might want to handle that better.