Question

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>
Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top