admin管理员组

文章数量:1323157

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 use toLocaleTimeString? – 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's formatToParts 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 hour 24 (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
 |  Show 8 more ments

2 Answers 2

Reset to default 8

Use 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