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

2020-07-09 10:18发布

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

标签: c# datetime
5条回答
你好瞎i
2楼-- · 2020-07-09 10:47

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

查看更多
太酷不给撩
3楼-- · 2020-07-09 10:55

Why would you like to parse 24:00:00 as a valid time expression when it would be like saying 09:05:60. The roof for time is 23:59:59.99999999999 and after that, it turns over to 00:00:00.

查看更多
\"骚年 ilove
4楼-- · 2020-07-09 10:57

Before parsing, do a simple search and replace - replace '24:00:00' with '00:00:00' and then parse as usual.

查看更多
Melony?
5楼-- · 2020-07-09 11:08

Convert to Minute.

if t.TotalMinutes < 0

double _24h = 0;
_24h = 1440 + t.TotalMinutes;
TimeSpan t = TimeSpan.FromMinutes(_24h);
查看更多
神经病院院长
6楼-- · 2020-07-09 11:08

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;
}
查看更多
登录 后发表回答