将默认日期转换为另一个日期(用户的本地时区) [英] Convert a default date to another date (local timezone of user)

查看:76
本文介绍了将默认日期转换为另一个日期(用户的本地时区)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的默认时间:19 Jul : 7:00pm CST

I have a default time in the following format: 19 Jul : 7:00pm CST

当用户访问显示该时间的页面时,我希望根据用户的本地时间将其转换为正确的时间.

When a user visits the page where this time is displayed, I'd like it to be converted to the correct time according to the user's local time.

有什么想法吗?

谢谢

推荐答案

首先,您需要输出希望其显示的日期,但请务必指定其时区(我在这里使用GMT,但您可以使用UTC, ETC).然后将其与本地加载时间交换掉(如果提供了原始时区,则由JavaScript自动处理).

First you need to 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">April 21, 2014 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天全站免登陆