So, I'm pretty new to JavaScript and I'm trying out some beginner projects on my own. I want to make a clock and add a 0 before single digit times. I have achieved this through multiple duplicate if-statements but when I try to translate that to a function I fail. I assume it is not working because I am trying to set a value to another value or I am comparing them by accident. I am in a bit of a mental knot at the moment.
function setTime() {
var today = new Date();
let hour = today.getHours();
let minute = today.getMinutes();
let seconds = today.getSeconds();
let period = '';
if (hour <= 11) {
period = 'AM';
} else if (hour >= 12) {
period = 'PM';
hour -= 12;
}
// function twoDigit(timeValue) {
// if (timeValue.toString().length === 1){
// timeValue = '0' + timeValue;
// }
// }
// twoDigit(seconds);
// twoDigit(minute);
// twoDigit(hour);
if (hour.toString().length === 1){
hour = '0' + hour;
}
if (minute.toString().length === 1){
minute = '0' + minute;
}
if (seconds.toString().length === 1){
seconds = '0' + seconds;
}
const timeDiv = document.getElementById('time-display');
timeDiv.innerHTML = hour + ':' + minute + ':' + seconds + ' ' + period;
document.body.appendChild(timeDiv);
}
setInterval(setTime, 1000);