date.getHours with 0 most stylish

I need to mount a JSON with a property in hours and minutes. I use a Timepicker on the front and it returns a date:

Fri Feb 15 2019 05:52:09 GMT-0200 (Horário de Verão  de Brasília)

To mount the JSON I do this:

var horaFormatada = (hora.getHours() < 10 ? '0' : '') + ":" + (hora.getMinutes() < 10 ? '0' : '') + hora.getMinutes();

Which results in:

05:52

This even works, but it seems kind of precarious to me and I would like a more elegant solution. Anyone have an idea?

Author: hkotsubo, 2019-02-15

2 answers

An alternative is to use padStart. Since this method is only available for strings, you first need to transform the numeric values into string, and then use 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 the case, 2)
  • the string used to fill in the beginning (in the 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 does not change (like 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 JavaScript's native date API does not provide many formatting options, but there is the option to use an external library, such as 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>
 1
Author: hkotsubo, 2019-02-15 18:21:52

Take a look at the timepicker documentation because it gives you the format you want it to return the date. For example, you said that it is returning to you (Fri Feb 15 2019 05:52:09 GMT-0200 (Brasilia Daylight Saving Time)), It is possible to pass the format you want the date to return, as exemplified in the documentation:

 $('#optionExample').timepicker({ 'timeFormat': 'g:ia' });
 2
Author: Luiz Heming, 2019-02-15 18:13:38