Javascript 显示不同的时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18645788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript display various time zones
提问by webfrogs
The following script should be displaying the current local time based on the offset of -10 (Hawaii), but it's not working.
以下脚本应该根据 -10(夏威夷)的偏移量显示当前本地时间,但它不起作用。
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>
回答by Matt Johnson-Pint
First of all, the code you've shown just returns the current local time. It doesn't even attemptto 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".
其次,您需要阅读时区标签 wiki。特别是,阅读标题为“时区!= 偏移”的部分。
Now it just so happens that Arizona and Hawaii don't currently use daylight saving time, so you couldadjust by offset if those were your only two concerns. But I'm sure you are looking for a more general solution.
现在恰好亚利桑那和夏威夷目前不使用夏令时,因此如果这些是您唯一关心的两个问题,您可以通过偏移进行调整。但我相信您正在寻找更通用的解决方案。
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.jswith the moment-timezoneplugin:
要正确执行此操作,您将需要一个实现 IANA 时区数据库的库。 我在这里列出了其中的几个。例如,这里是使用moment.js和moment-timezone插件显示洛杉矶当前时间的示例:
moment().tz("America/Los_Angeles").format("h:mm a")
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.
如果您只是想寻找一种快速简便的方法在您的网站上放置一个特定时区的时钟,那么我建议您使用timeanddate.com 提供的免费解决方案。
回答by Paul S.
Write a function to move a Dateby some offset in minutes/your choice
编写一个函数,以分钟为单位将日期移动一些偏移量/您的选择
function offsetDate(offsetMinutes, d) {
if (d) d = new Date(d);
else d = new Date();
if (offsetMinutes) d.setUTCMinutes(d.getUTCMinutes() + offsetMinutes);
return d;
}
offsetDate(-10*60); // Thu Sep 05 2013 12:03:06 GMT+0100 (GMT Daylight Time)
Now use UTCfunctions to get the time
现在使用UTC函数来获取时间