-2

My date() function wont show zeros no matter what, instead of showing 14:20 or 14:02, the zero is missing and all it shows is 14:2

getDate() {
  let data = new Date();
  let dia = data.getDate()+ '/' + (data.getMonth() + 1) + '/' + data.getFullYear();
  let hora = data.getHours() + ':' + data.getMinutes() + ' de ' + dia;
  return hora;
}, 
Gabriel Costa
  • 374
  • 1
  • 3
  • 16

3 Answers3

0

This is expected behaviour. The Date object won't format numbers for you. Try using this:

const now = new Date();
console.log(("0" + now.getMinutes()).slice(-2))

("0" + number).slice(-2)

alistair
  • 565
  • 5
  • 15
0

function getDate() {
  let data = new Date();
  let dia = data.getDate()+ '/' + (data.getMonth() + 1) + '/' + data.getFullYear();
const min = data.getMinutes() < 10 ? '0' + data.getMinutes() : data.getMinutes();


  let hora = data.getHours() + ':' + min + ' de ' + dia;
  return hora;
};

console.log(getDate());
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
-1

You can create a padding function to prepend the missing zeroes.

function pad(number, padding) {
  return (padding + number).substr(-padding.length);
}

function getDate() {
  let data = new Date();
  let dia = [
    pad(data.getDate(), '00'),
    pad((data.getMonth() + 1), '00'),
    pad(data.getFullYear(), '0000'),
  ].join('/');
  let hora = [
    pad(data.getHours(), '00'),
    pad(data.getMinutes(), '00')
  ].join(':');
  return hora + ' de ' + dia;
}

function pad(number, padding) {
  return (padding + number).substr(-padding.length);
}

console.log(getDate());
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132