I want to format the time so that the seconds are displayed differently. However, the javascript method Date.toLocaleTimeString
does not return the expected result. This has been mentioned several times on Stackoverflow.
Code:
let datetimeString = '2022-08-02T16:01:01 02:00';
let dateObj = new Date(datetimeString);
let hourMinuteString = dateObj.toLocaleTimeString('de', {hour: '2-digit', minute: '2-digit'});
let secondString = dateObj.toLocaleTimeString('de', {second: '2-digit'});
let tdString = `<time >${hourMinuteString}</time>`;
tdString = `<time >:${secondString}</time>`;
console.log(tdString);
Output:
<time >16:01</time><time >:1</time>
I know that my desired result can be achieved with ${secondString.padStart(2, '0')}
. But I wonder why this string padding has to be produced manually for JS engines like V8 (Chrome 103.0.5060.134) or Node.js (v18.7.0), when Intl.DateTimeFormatOptions
allows the choice between 2-digit and numeric for the seconds formatting.
I have consulted the ECMAScript specification for this. As far as I understand it, section 12.3.2 specifies the following rule: If "2-digit" is requested for second, Intl.NumberFormat
with {minimumIntegerDigits: 2, useGrouping: false}
shall be used for formatting.
I am aware that specifications are disregarded for archaic reasons and any bugs remain unfixed due to possible breaking changes. But I don't understand why this is necessary here: if you really need 2-digit formatting, you solve your problem with padStart. I already looked at the V8 implementation in js-date-time-format.cc, but don't see there why "2-digit" doesn't lead to "ss".
A similar problem was reported as a bug in 2015. A locale issue was suspected behind it, but the problem is now considered fixed.
I'm not familiar with understanding specs correctly - it's quite possible I'm getting it wrong. Can someone enlighten me or is it simply a bug?
CodePudding user response:
Looks like a bug. crbug.com/v8/13168 has been filed.