DateTime无法以HH:mm:ss格式解析24:00:00 [英] DateTime fails to parse 24:00:00 in the HH:mm:ss format
问题描述
在解析某些时间时,我注意到一个非常有趣的错误。
DateTime
未能解析 24:00:00
。在一些谷歌搜索和堆栈下,我发现 DateTime
只识别 00-23
(这是什么? ),因此如果您输入的是 24:00:00
,则表示您不走运。您会认为有人会把 24:00:00
等同于 00:00:00
(
我的问题是,如何允许 DateTime
允许我解析 24:00:00
?
不幸的是,由于说明原因,我无法使用 NodaTime
(对不起,乔恩。我爱您的图书馆) 。
以下实验:
An < 2014-03-18 24:00:00
的code> input 会出现以下错误。
输入
c> 2014-03-18 23:59:59 将成功解析。
输入
的2014-03-19 00 :00:00`将成功解析。
DateTime类不提供 24小时支持。
小时(HH / H,24小时制)必须为0- 23(含)。这就是为什么00:00:00有效但24:00:00无效的原因。
将24:00:00更改为00:00:00(在解析之前) ),并在需要时提前一天(解析后)。
以下内容将在提供的格式(但最多24小时),尽管它不考虑任意格式。支持不同格式的字符串只会增加额外的复杂性。 (输入,@ 24:(\d\d:\d\d)$, 00:$ 1);
var res = DateTime.ParseExact(wrap, yyyy-MM-dd HH:mm:ss,null);
return包装成!=输入
? res.AddDays(1)
:res;
}
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;
}
这篇关于DateTime无法以HH:mm:ss格式解析24:00:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!