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>