Javascript显示各种时区 [英] Javascript display various time zones

查看:100
本文介绍了Javascript显示各种时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下脚本应根据偏移量-10(夏威夷)显示当前本地时间,但它不起作用。

The following script should be displaying the current local time based on the offset of -10 (Hawaii), but it's not working.

无法弄清楚我哪里出错了。

Can't figure out where I'm going wrong.

<h3>Current Time in Arizona is 
<script type="text/javascript">
<!--
    var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()

    if (minutes < 10)
    minutes = "0" + minutes

    var suffix = "AM";
    if (hours >= 12) {
    suffix = "PM";
    hours = hours - 12;
    }
    if (hours == 0) {
    hours = 12;
    }

    document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
//-->
</script>
</h3>


推荐答案

首先,您展示的代码只是返回当前本地时间。它甚至没有尝试在特定时区更改它。

First of all, the code you've shown just returns the current local time. It doesn't even attempt to change it for a specific time zone.

其次,您需要阅读时区标签维基。特别是,请阅读标题为时区!=偏移的部分。

Secondly, you need to read the timezone tag wiki. In particular, read the section titled "Time Zone != Offset".

现在碰巧亚利桑那州和夏威夷目前不使用夏令时,所以你如果这是你唯一的两个问题,那么可以通过抵消进行调整。但我确信您正在寻找更通用的解决方案。

Now it just so happens that Arizona and Hawaii don't currently use daylight saving time, so you could adjust by offset if those were your only two concerns. But I'm sure you are looking for a more general solution.

要做到这一点,您需要一个实现IANA时区数据库的库。 我在此列出了其中几个。例如,以下是使用 moment.js 并使用 moment-timezone 插件:

To do it properly, you will need a library that implements the IANA time zone database. I list several of them here. For example, here is an example of displaying the current time in Los Angeles using moment.js with the moment-timezone plugin:

moment().tz("America/Los_Angeles").format("h:mm a")

如果您只是想快速简便地在特定时区的网站上放一个时钟,那么我建议您使用 timeanddate.com提供的免费解决方案

If you're just looking for a quick and easy way to put a clock on your web site for a particular time zone, then I recommend using the free solution offered by timeanddate.com.

这篇关于Javascript显示各种时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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