views:

59

answers:

2

I need to offset the time by an hour if it's currently DST in the Pacific Time Zone. How can I determine the current daylight savings status of the Pacific Time Zone, regardless of the user's local timezone?

Here's what I have so far. "dst" in line 4 is just a placeholder for a function that would tell me if daylight savings time is active in that zone.

function checkTime() {  
    var d = new Date();  
    var hour = d.getUTCHours();  
    var offset = dst ? 7 : 8; // is pacific time currently in daylight savings?

    // is it currently 6 AM, 2 PM, or 10 PM?
    if (hour === ((6 + offset) % 24) || hour === ((14 + offset) % 24) || hour === ((22 + offset) % 24)) {  
      // do stuff
    }
}

checkTime();
+2  A: 

The only real way you will be able to tell for sure is if you have the DST information (including any updates) available on a server you can ask. The user's PC does not need to even have the timezone information installed.

Then you need a "dynamic" script to get the DST status.

Possible methods: Reference a PHP/ASPX/JSP/CFM/ASP page that generates a javascript to set a variable that indicates if DST is active or not, or the current number of minutes offset.

Write the script in your (hopefully dynamic) page directly.

Use AJAX/REST/JASON to access a Date/Time service somewhere that can tell you the DST status or number of minutes offset from UTC for a timezone/location.

Minutes is preferable to hours because DST offsets are actually in minutes around the world, not hours.

Roger Willcocks
+1  A: 

I've also struggled with this before in a PHP based website which is supposed to display the "world clock". There's no nice way to achieve this in JS and even then, you're heavily dependent on the client's environment. You really need to do this task in the server side language you're using.

If it happens that you're using PHP as well, then you may find this snippet useful:

function get_offset_with_DST($timezone_name) {
    $default_timezone = date_default_timezone_get();
    date_default_timezone_set($timezone_name);
    $offset_with_DST = date('Z') / 3600;
    date_default_timezone_set($default_timezone);
    return $offset_with_DST;
}

and then in JS:

<script>var offsetWithDST = <?= get_offset_with_DST('US/Pacific'); ?>;</script>

For a list of all supported timezone names in PHP, check this page.

BalusC