admin管理员组文章数量:1323323
The below call returns 24:00
in latest Chrome & Opera, while it previously returned 00:00
, is this a by design behavior?
const [, time] = new Date(2020, 1, 1, 0, 0).toLocaleDateString("en-us",
{
hour12: false,
hour: "2-digit",
minute: "2-digit"
}).split(", ");
console.info(time); // 24:00
The below call returns 24:00
in latest Chrome & Opera, while it previously returned 00:00
, is this a by design behavior?
const [, time] = new Date(2020, 1, 1, 0, 0).toLocaleDateString("en-us",
{
hour12: false,
hour: "2-digit",
minute: "2-digit"
}).split(", ");
console.info(time); // 24:00
Share
edited Mar 12, 2020 at 13:32
T.J. Crowder
1.1m200 gold badges2k silver badges1.9k bronze badges
asked Mar 12, 2020 at 13:29
JsCoderJsCoder
2,2338 gold badges35 silver badges66 bronze badges
13
-
1
What happens if you specify
”en-GB”
(which uses 24-hour clock natively) instead of”en-US”
? I suspect it’s related to how 12-hour clocks (which en-US use by default) never show “00:00” for midnight use show “12:00” instead - so maybe there’s a setting for “don’t show all-zeroes”? – Dai Commented Mar 12, 2020 at 13:36 - 1 @Dai that fixed it – JsCoder Commented Mar 12, 2020 at 13:37
-
2
Just curious, why are you using
toLocaleDateString
to format a time? Wouldn't it make more sense to usetoLocaleTimeString
? – Heretic Monkey Commented Mar 12, 2020 at 13:38 -
3
Fair enough. Just wondering about "right tool for the job" kind of thing. I'd probably use
Intl.DateTimeFormat
'sformatToParts
myself, then you have full control over which parts you want to keep, and which you want to throw away. BTW, ECMAScript says that if the hour is 0, and the hour cycle is defined as 24 hours, make hour24
(step 14.c.vi.). – Heretic Monkey Commented Mar 12, 2020 at 13:49 - 1 @user1514042 I don't know enough about it to give you a good answer – Huangism Commented Mar 12, 2020 at 13:55
2 Answers
Reset to default 8Use hourCycle
instead of hour12
and set it to h23
.
const [, time] = new Date(2020, 1, 1, 0, 0).toLocaleDateString("en-us",
{
hourCycle: "h23",
hour: "2-digit",
minute: "2-digit"
}).split(", ");
console.info(time); // 00:00
It looks to me like Chrome (or its V8 engine) has updated to match the specification, which says in Step 18(e)(vi):
If p is "hour" and dateTimeFormat.[[HourCycle]] is "h24", then If v is 0, let v be 24.
That specification hasn't changed, but it looks like they must have fixed a bug. (I didn't immediately find one in the V8 or Chromium issue list, but...)
Interestingly, Firefox shows 00:00
, not 24:00
.
本文标签: javascripttoLocaleDateString returns unexpected formatted timeStack Overflow
版权声明:本文标题:javascript - toLocaleDateString returns unexpected formatted time - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742140542a2422563.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论