Displaying date/time in user#39;s timezone - on client side(在用户的时区显示日期/时间 - 在客户端)
问题描述
我有一个在每个页面上显示日期时间戳的 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>
这篇关于在用户的时区显示日期/时间 - 在客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在用户的时区显示日期/时间 - 在客户端
 
				
         
 
            
        基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				