问题描述
我有一个在每个页面上显示日期时间戳的 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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)