Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime fails to parse 24:00:00 in the HH:mm:ss format

Tags:

c#

datetime

I noticed quite an interesting error when parsing some times.

DateTime fails to parse 24:00:00. Under some Googling and Stacking, I found out that DateTime only recognizes 00 - 23 (what the?????), so if your input is 24:00:00, you're out of luck. You would think someone would put in a condition to equate 24:00:00 as 00:00:00 (the midnight), but not yet..

My question is, how do I allow DateTime to allow me to parse 24:00:00?

Unfortunately I cannot to use NodaTime under specification reasons (sorry Jon. I love your library though).

Experimentation below:

An input of 2014-03-18 24:00:00 would present the following error. Expected.

enter image description here


An input of 2014-03-18 23:59:59 would successfully parse. Expected.

enter image description here


An input of 2014-03-19 00:00:00` would successfully parse. Expected.

enter image description here

like image 969
theGreenCabbage Avatar asked Mar 25 '14 18:03

theGreenCabbage


2 Answers

There is no "24th hour" support in the DateTime class.

The hour (HH/H, 24-hour clock) must be 0-23, inclusive. This is why 00:00:00 is valid, but 24:00:00 is not.

Change 24:00:00 to 00:00:00 (before parsing) and, if needed, advance the day as appropriate (after parsing).


The following will work on times in the provided format (but only up to the 24th hour) although it doesn't account for an arbitrary format. Supporting different format strings only adds additional complications.

DateTime ParseWithTwentyFourthHourToNextDay (string input) {
    var wrapped = Regex.Replace(input, @"24:(\d\d:\d\d)$", "00:$1");
    var res = DateTime.ParseExact(wrapped, "yyyy-MM-dd HH:mm:ss", null);
    return wrapped != input
        ? res.AddDays(1)
        : res;
}
like image 142
user2864740 Avatar answered Sep 24 '22 18:09

user2864740


24:00:00 doesn't exist. It is 00:00:00 - 23:59:59

like image 23
mkincade3 Avatar answered Sep 24 '22 18:09

mkincade3