Javascript display various time zones

二次信任 提交于 2019-12-10 10:58:03

问题


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>

回答1:


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.

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")

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.




回答2:


Write a function to move a Date by 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 UTC functions to get the time



来源:https://stackoverflow.com/questions/18645788/javascript-display-various-time-zones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!