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

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

问题描述

我有一个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

加州用户会看到:


2009年12月12日3:00 pm

December 12, 2009 3:00 pm

任何建议?

推荐答案

p>这里是如何用美妙的渐进增强来实现的:

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天全站免登陆