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.
An input
of 2014-03-18 23:59:59
would successfully parse. Expected.
An input
of 2014-03-19 00:00:00` would successfully parse. Expected.
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;
}
24:00:00 doesn't exist. It is 00:00:00 - 23:59:59
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With