Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Js

Idiom #261 Format time hours-minutes-seconds

Assign to the string x the value of fields (hours, minutes, seconds) of the date d, in format HH:MM:SS.

const d = new Date();

let hr = d.getHours();
let min = d.getMinutes();
let sec = d.getSeconds();

if ( hr.toString().length === 1 ) {
  hr = '0' + hr;
}

if ( min.toString().length === 1 ) {
  min = '0' + min;
}

if ( sec.toString().length === 1 ) {
  sec = '0' + sec;
}

const x = '' + hr + ':' + min + ':' + sec;

Call `.toString().length` to check if zero padding needed.
let f = new Intl.DateTimeFormat(undefined, {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hourCycle: 'h24'
}), x = f.format(d)
with Ada.Calendar.Formatting;
X : constant String :=
    Ada.Calendar.Formatting.Image (D) (12 .. 19);

Image returns date as well therefore the slice

New implementation...
< >
programming-idioms.org