javascript date to string

You will need to pad with “0” if its a single digit & note that getMonth returns 0..11 not 1..12

function printDate() {
  const temp = new Date();
  const pad = (i) => (i < 10) ? "0" + i : "" + i;

  return temp.getFullYear() +
    pad(1 + temp.getMonth()) +
    pad(temp.getDate()) +
    pad(temp.getHours()) +
    pad(temp.getMinutes()) +
    pad(temp.getSeconds());
}

console.log(printDate());

Leave a Comment