简体   繁体   中英

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 ?

dayNames = ["DOM", "LUN", "MAR", "MER", "GIO", "VEN", "SAB"],

dayNames[date.getDay()]

to show a string with your day.

have a look here to see a personal working example https://fiddle.sencha.com/#view/editor&fiddle/1kfh

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> 

Use Below Code and Check it. HTML

 <div id="time"></div>
  <div id="day"></div>

Javascript

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

    function startTime() {
    var today = new Date(),
    ndays = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]
    h = checkTime(today.getHours()),
    m = checkTime(today.getMinutes());
    s = checkTime(today.getSeconds());
    dn = today.getDay(),

    document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
    var d=ndays[dn];
    document.getElementById('day').innerHTML=d;
    t = setTimeout(function () {
    startTime()
        }, 500);
    }
    startTime();
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM