简体   繁体   中英

Live Digital clock with timezones

I have a digital clock that is running and it works great but I want to have multiple clocks running with different timezones. I am on the west coast and I would like the time to be different when people look at it in different timezones. How can I accomplish this?

function displayTime() {
        var currentTime = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();
        var meridiem = "AM";  

        if (hours > 12) {
            hours = hours - 12; 
            meridiem = "PM"; 
        }

        if (hours === 0) {
            hours = 12;
        }

        if(hours < 10) {

            hours = "0" + hours;
        }

        if(minutes < 10) {
            minutes = "0" + minutes;
        }
        if(seconds < 10) {
            seconds = "0" + seconds;
        }

        var clockDiv = document.getElementById('clock');

        clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
    }

    displayTime();

    setInterval(displayTime, 1000);

}); 

To get the time in any timezone based on the current system time (which might be wrong, but that may not really matter), create a Date and just adjust the UTC time values by the required offset, then use UTC methods to build your formatted string.

eg

 /* Return a time string in h:m:sa/p format ** ** @param {number} offsetInMinutes - offset of required timezone in minutes ** @returns {string} formatted time string */ function getTimeInZone(offsetInMinutes) { function z(n) {return (n<10?'0':'') + n;} var d = new Date(); d.setUTCMinutes(d.getUTCMinutes() + offsetInMinutes); var h = d.getUTCHours(); return z(h%12||12) + ':' + z(d.getUTCMinutes()) + ':' + z(d.getUTCSeconds()) + ' ' + (h<12? 'am' : 'pm'); } // Time at UTC-08:00 document.write(getTimeInZone(-480)); 

You say you're "on the west coast", but not of where, so I'll assume USA where the likely timezone offset is UTC-08:00 (-480 minutes). So to always show the time in that timezone (with the usual caveat that the system clock may not be correct), you'd do:

getTimeInZone(-480);

Also note that innerText is a IE proprietary property and not supported in all browsers.

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