date.getHours with 0 more elegant

Asked

Viewed 203 times

2

I need to assemble 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 build 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 to me a little precarious and would like a more elegant solution. Someone has an idea?

2 answers

2

takes a look at the timepicker documentation because you can inform the format you want it to return the date. For example, you said that it is returning 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' });

1


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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.