I use javascript Date.prototype.toLocaleTimeString() (or equivalently: Intl.DateTimeFormat())
I want a representation of time (especially minute and second) WITHOUT leading zero (when min/sec is less than 10).
Ex. 13:2:3 or 1:2:3 PM (NOT 13:02:03 or 1:02:03 PM)
But I can't achieve this:
const date = new Date('2/21/2021, 13:2:3')
const t1 = date.toLocaleTimeString('en-US') // 1:02:03 PM
const t2 = date.toLocaleTimeString('en-US', {timeStyle: 'medium'}) // 1:02:03 PM
const t3 = date.toLocaleTimeString('en-US', {timeStyle: 'short'}) // 1:02 PM
const t4 = date.toLocaleTimeString('en-US', {minute: '2-digit', second: '2-digit'}) // 02:03
const t5 = date.toLocaleTimeString('en-US', {minute: 'numeric', second: 'numeric'}) // 02:03
console.log(t1 + '\n' + t2 + '\n' + t3 + '\n' + t4 + '\n' + t5)
According to MDN:
minute
The representation of the minute. Possible values are
"numeric","2-digit".second
The representation of the second. Possible values are
"numeric","2-digit".
NOTE: I don't want to use an external library, for this.
Not sure why you'd want to do this, but hey.
You can use formatToParts and remove the leading zero from whatever type you want:
const date = new Date('2/21/2021, 13:02:03')
const formatter = new Intl.DateTimeFormat(navigator.language, {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
});
const dateString = formatter.formatToParts(date).map(({type, value}) => {
switch (type) {
case 'minute':
case 'second':
return value.replace(/^0/, '');
default:
return value;
}
}).join('');
console.log(dateString)