-1

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;
}, 

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
  • 336
  • 2
  • 12
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
  • 14,761
  • 4
  • 84
  • 60
-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
  • 31,606
  • 11
  • 65
  • 114