2

i have a string which contains date time this...

string S="08/18/2013 24:00:00"
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy HH:mm:ss", null);

i want to parse it into date time but shows an exception like this. The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

please tell me any solution for this problem.

4
  • 1
    Just a thought there is no time 24:00:00. Dont know if that is your problem though. Commented Jul 25, 2013 at 11:37
  • 1
    @ckv: There is in ISO-8601. It's "the end of the day" basically. Commented Jul 25, 2013 at 11:39
  • @JonSkeet Thanks for that interesting fact. Commented Jul 25, 2013 at 11:40
  • @user1882191 Consider to accept one of this answers.. Commented Jul 26, 2013 at 8:38

3 Answers 3

10

The problem is with the hour being 24. DateTime doesn't support this, as far as I'm aware.

Options:

  • Use my Noda Time project which does support 24:00:00, but basically handles it by adding a day (it doesn't preserve a difference between that and "end of previous day")
  • Keep using DateTime, manually replace "24:00:00" with "00:00:00" when it occurs, and remember to add a day afterwards

If you want to preserve the information that it was actually "end of the day" you'd need to do that separately, and keep the information alongside the DateTime / LocalDateTime.

You should also parse with the invariant culture as other answers have suggested - you're not trying to parse a culture-specific string; you know the exact separators etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice catch, I didn't notice 24 :)
1
string S="08/18/2013 00:00:00";  // here is the first problem occurred
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

Comments

0

From The "HH" Custom Format Specifier

The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight.

So, using 24 as an hour is invalid on this case.

Try with hh format with 00 instead like;

string S = "08/18/2013 00:00:00";
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);

Here a DEMO.

If you really want to use 24:00:00 as a hour, take a look Noda Time which developed by Jon.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.