在用户的时区中显示日期/时间 - 在客户端 [英] Displaying date/time in user's timezone - on client side

查看:22
本文介绍了在用户的时区中显示日期/时间 - 在客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 应用程序,它在每个页面上显示日期时间戳,例如:

<块引用>

2009 年 12 月 12 日下午 6:00

我想动态检测用户的时区并使用 JavaScript 更改显示.

所以纽约用户会看到:

<块引用>

2009 年 12 月 12 日下午 6:00

而加州用户会看到:

<块引用>

2009 年 12 月 12 日下午 3:00

有什么建议吗?

解决方案

这里是如何使用美妙的渐进增强"来做到这一点:

输出您希望它出现的日期,但一定要指定其时区(我在这里使用 GMT,但您可以使用 UTC 等).然后在加载时将其与本地时间交换(如果提供了原始时区,则由 JavaScript 自动处理).

2009 年 12 月 12 日下午 6:00 GMT

<script type="text/javascript">var timestamp = document.getElementById('timestamp'),t = 新日期(timestamp.innerHTML),小时 = t.getHours(),min = t.getMinutes() + '',下午 = 假,月份 = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];如果(小时 > 11){小时 = 小时 - 12;下午 = 真;}如果(小时== 0)小时= 12;if(min.length == 1) min = '0' + min;timestamp.innerHTML = Months[t.getMonth()] + ' ' + t.getDate() + ', ' + t.getFullYear() + ' ' + hours + ':' + min + ' ' + (pm ? '下午' : '上午');

I have a web application that displays datetime stamps on every page, for example:

December 12, 2009 6:00 pm

I would like to dynamically detect the user's timezone and alter the display using JavaScript.

So the New York user would see:

December 12, 2009 6:00 pm

While the California user would see:

December 12, 2009 3:00 pm

Any suggestions?

解决方案

Here is how you could do it with the wonderful "progressive enhancement":

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>

这篇关于在用户的时区中显示日期/时间 - 在客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆