An alternative is to use padStart. Since this method is only available for strings, you first need to turn the numeric values into string, and then use the padStart:
let d = new Date();
let horaFormatada = d.getHours().toString().padStart(2, '0') + ':' +
d.getMinutes().toString().padStart(2, '0');
console.log(horaFormatada);
The parameters are:
- the size of the final string (in this case, 2)
- the string used to fill at start (in case,
'0')
That is, if the value is less than 10 (like 1, for example), the result will be 01. If the value is greater than 10, it is not changed (such as 16, for example).
If you want to organize the code, you can put this in a function:
function formatarValor(valor) {
return valor.toString().padStart(0, 2);
}
let d = new Date();
let horaFormatada = formatarValor(d.getHours()) + ':' +
formatarValor(d.getMinutes());
console.log(horaFormatada);
Unfortunately the native Javascript date API does not provide many formatting options, but there is the option to use an external library such as the Moment js.:
// data atual
let d = moment();
let horaFormatada = d.format('HH:mm');
console.log(horaFormatada);
// se você já tiver um Date, também pode criar um moment a partir dele:
let date = new Date();
d = moment(date);
horaFormatada = d.format('HH:mm');
console.log(horaFormatada);
<script src="https://momentjs.com/downloads/moment.min.js"></script>