How to format date for dd/mm/yyyy hh:mm using Javascript?

Asked

Viewed 699 times

2

The date I have this way:

"Fri Sep 22 2017 14:42:35 GMT-0300"

I need to format it to the following format:

dd/mm/yyyy hh:mm

How could I do this using Javascript or Angular?

1 answer

5


I needed it once, so I did the basics:

<script>
var data = new Date("Fri Sep 22 2017 14:42:35 GMT-0300");
var dia = data.getDate(); dia = zeroAEsquerda(dia, 2);
var mescru = data.getMonth();var mes = data.getMonth(); mes += 1; mes = zeroAEsquerda(mes, 2);
var ano = data.getFullYear();
var dataAtual = dia+'/'+mes+'/'+ano;
var horaAtual       = data.getHours();          // 0-23
var minutoAtual     = data.getMinutes();        // 0-59
var segundoAtual    = data.getSeconds();        // 0-59
console.log('Data: '+dia+'/'+mes+'/'+ano+' - '+horaAtual+':'+minutoAtual+':'+segundoAtual);
function zeroAEsquerda(str, length) {
  const resto = length - String(str).length;
  return '0'.repeat(resto > 0 ? resto : '0') + str;
}
</script>

Browser other questions tagged

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