Ezhno Ezhno - 17 days ago 7
Javascript Question

Display day of the week, hours and minutes, and date

I would like to adapt this script so it can also display the day of the week and the date.

(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}

function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes());
document.getElementById('time').innerHTML = h + ":" + m;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();


I though about adding a
getDay();
but I don't know how to add it in the function to be honest. Knowing that the day and date must update automaticaly on the page, that will stay open for days.. (It's a display that will almost always stay on.)

Any idea ?

Answer

Add the month and day names to array, and then use getDay(), getDate(), getMonth() and getFullYear():

(function () {
    function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

    function startTime() {
    	var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
      	  days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]
    
        var today = new Date(),
            d = today.getDay(),
            f = today.getDate(),
            m = today.getMonth(),
            y = today.getFullYear(),
            
            h = checkTime(today.getHours()),
            i = checkTime(today.getMinutes());
        
        var val = days[d]+', '+f+' '+months[m]+' '+y+' - '+h+':'+i;
        
        document.getElementById('time').innerHTML = val;
        
        t = setTimeout(function () {
            startTime()
        }, 500);
    }
    
    startTime();
})();
<div id="time"></div>