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

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

问题描述

我有一个在每个页面上显示日期时间戳的 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>

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

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