Parsing time from ddMMMyyyyhhmm format string (with month name)

I’m kind of stuck in a problem when I can’t parse the date and time from a string that I am reading from a text file. The string I get has the following format:

05SEP1998 2400

and I'm trying to parse a 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 when parsing, the above code throws a FormatException:

String was not recognized as a valid DateTime.

Can someone help me solve this problem?

+5
source share
2 answers

hhis 12 hours hh- 24 hours. However, it should be in the range 0-23, not 24. If you cannot easily change the way you create these date strings, you can analyze 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);

, , dateTimeStr . , .

+1

24 . 0-23. .

?

DateTime ,

DateTime dt = new DateTime(1998, 9, 5, 24, 0, 0);

, Hour. minute and second parameters descrive an un-representable DateTime

0

All Articles