簡體   English   中英

帶時區的實時數字時鍾

[英]Live Digital clock with timezones

我有一個正在運行的數字時鍾,它運行良好,但是我想讓多個時鍾在不同時區運行。 我在西海岸,所以我希望人們在不同時區看到的時間會有所不同。 我該怎么做?

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);

}); 

要基於當前系統時間獲取任何時區的時間(這可能是錯誤的,但這可能並不重要),請創建一個Date並僅按所需的偏移量調整UTC時間值,然后使用UTC方法構建格式化的串。

例如

 /* 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)); 

您說您在“西海岸”,但不在哪個地方,所以我假設美國的時區偏移量可能是UTC-08:00(-480分鍾)。 因此,要始終顯示該時區的時間(通常會警告系統時鍾可能不正確),您可以這樣做:

getTimeInZone(-480);

還要注意, innerText是IE的專有屬性,並非所有瀏覽器都支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM