简体   繁体   English

带时区的实时数字时钟

[英]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. 要基于当前系统时间获取任何时区的时间(这可能是错误的,但这可能并不重要),请创建一个Date并仅按所需的偏移量调整UTC时间值,然后使用UTC方法构建格式化的串。

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). 您说您在“西海岸”,但不在哪个地方,所以我假设美国的时区偏移量可能是UTC-08:00(-480分钟)。 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. 还要注意, innerText是IE的专有属性,并非所有浏览器都支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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