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?

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
Pankaj
  • 259
  • 3
  • 16

2 Answers2

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.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • I find your approach wrong. Why? Because in this code for example `"05SEP1998 2400"` you assume that 24 is 0th Hour of 5th Sep. But Infact it is 0th Hour of 6th Sept. Hence realdate is `"06SEP1998 0000"` – Nikhil Agrawal Jun 30 '12 at 13:04
  • That's why I have `dateTime += TimeSpan.FromHours(24);`. The example date resolves to `9/6/1998 12:00:00 AM` (or `06SEP1998 0000`). – Tim S. Jun 30 '12 at 19:55
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

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208