5

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?

4

2 に答える 2

1

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.

于 2012-06-30T11:53:50.720 に答える
0

There are 24 hours in a day. But while writing we say its from 0-23. It is giving exception on hours format.

How I found out?

I tried creating a DateTime object from your string like

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

It gave error on Hours that Hour. minute and second parameters descrive an un-representable DateTime

于 2012-06-30T11:54:18.893 に答える