問題描述
我有一個在每個頁面上顯示日期時間戳的 Web 應用程序,例如:
I have a web application that displays datetime stamps on every page, for example:
2009 年 12 月 12 日下午 6:00
December 12, 2009 6:00 pm
我想動態檢測用戶的時區并使用 JavaScript 更改顯示.
I would like to dynamically detect the user's timezone and alter the display using JavaScript.
所以紐約用戶會看到:
2009 年 12 月 12 日下午 6:00
December 12, 2009 6:00 pm
雖然加利福尼亞用戶會看到:
While the California user would see:
2009 年 12 月 12 日下午 3:00
December 12, 2009 3:00 pm
有什么建議嗎?
推薦答案
以下是您可以如何通過精彩的漸進式增強"來做到這一點:
Here is how you could do it with the wonderful "progressive enhancement":
輸出你希望它出現的日期,但一定要指定它的時區(我在這里使用 GMT,但你可以使用 UTC 等).然后將其替換為加載時的本地時間(如果提供了原始時區,則由 JavaScript 自動處理).
Output the date where you want it to appear, but be sure to specify its timezone (I use GMT here, but you could use UTC, etc). Then swap it out with the local time on load (Automatically handled by JavaScript if the original timezone is provided).
<div id="timestamp">December 12, 2009 6:00 pm GMT</div>
<script type="text/javascript">
var timestamp = document.getElementById('timestamp'),
t = new Date(timestamp.innerHTML),
hours = t.getHours(),
min = t.getMinutes() + '',
pm = false,
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
if(hours > 11){
hours = hours - 12;
pm = true;
}
if(hours == 0) hours = 12;
if(min.length == 1) min = '0' + min;
timestamp.innerHTML = months[t.getMonth()] + ' ' + t.getDate() + ', ' + t.getFullYear() + ' ' + hours + ':' + min + ' ' + (pm ? 'pm' : 'am');
</script>
這篇關于在用戶的時區顯示日期/時間 - 在客戶端的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!