0

I'm using javascript to display the current (live) date/time on a website. I want all the numbers (date, hour, minute, second) to always display with 2 digits. So if a number is (0-9) it is prefixed with a '0'

I've managed to do this for the time counter. But I can't seem to work the same code into getDate without breaking the script.

If someone could help with that it'd be greatly appreciated and also confirm if my approach isn't massively overcomplicated!

function showDateTime() {
  var currentDate = document.getElementById("date");
  var currentTime = document.getElementById("time");

  var date = new Date();
  var dayList = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  var monthNames = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];
  var dayName = dayList[date.getDay()];
  var monthName = monthNames[date.getMonth()];
  var today = `${dayName} ${date.getDate()} ${monthName}`;

  var hour = ('0'+date.getHours()).substr(-2);
  var min = ('0'+date.getMinutes()).substr(-2);
  var sec = ('0'+date.getSeconds()).substr(-2);

  var time = hour + ":" + min + ":" + sec;
  currentDate.innerText = `${today}`;
  currentTime.innerText = `${time}`;
}
setInterval(showDateTime, 1000);
<div id="date"></div>
<div id="time"></div>
user1406440
  • 1,329
  • 2
  • 24
  • 59

1 Answers1

0
const date = new Date();
const now = date.toLocaleTimeString(); // "11:33:01"

You could also use const instead of var because the value will never change.

    function showDateTime() {
  const currentDate = document.getElementById("date");
  const currentTime = document.getElementById("time");

  const date = new Date();
  const dayList = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const monthNames = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];

  const dayName = dayList[date.getDay()];
  const monthName = monthNames[date.getMonth()];
  const today = `${dayName} ${date.getDate()} ${monthName}`;

  const time = date.toLocaleTimeString(); 

  currentDate.innerText = `${today}`;
  currentTime.innerText = `${time}`;
}
setInterval(showDateTime, 1000);
ManuelMB
  • 1,254
  • 2
  • 8
  • 16