0

I have a real-time clock on my website that uses JavaScript to function however it grabs the current time from the user's computer, therefore the time zone the clock works in is different for each user. How can I modify the code below so that the clock only uses Central Standard Time, USA (GMT - 6)?

function updateClock () {
    var currentTime = new Date();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

    var timeOfDay = (currentHours < 12) ? "AM" : "PM";
    currentHours = (currentHours > 12) ? currentHours-12 : currentHours;
    currentHours = (currentHours == 0) ? 12 : currentHours;

    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

    document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
user1710563
  • 387
  • 2
  • 7
  • 18
  • 2
    http://stackoverflow.com/q/1091372/362536 – Brad Oct 02 '12 at 02:35
  • @Brad That help a little bit, but I'm new to javascript so...not so much – user1710563 Oct 02 '12 at 02:46
  • I'm not sure how to help you if you can't explain how that prior question doesn't directly answer your question. Explain what you are confused about. – Brad Oct 02 '12 at 02:47
  • Confused about how to implement the time zone offset into the above code. Would I do "var currentTime = new Date().TimezoneOffset();" and it will only show CST? Excuse my dumbness about this – user1710563 Oct 02 '12 at 02:52
  • plus, if you want a **fixed** time zone, why not set on the server instead of calculating it on the client? – RASG Oct 02 '12 at 02:52
  • @RASG That'd work as well...now how to do that? – user1710563 Oct 02 '12 at 02:56
  • @user1710563, See this post for adding/subtracting two Date objects: http://stackoverflow.com/q/674721/362536 – Brad Oct 02 '12 at 02:57
  • you can search google for all kind of clocks. php, java, flash, etc – RASG Oct 02 '12 at 02:58
  • Nobody seems to have suggested working with the UTC values after modifying by CST offset and therefore letting you complety ignore local time – Paul S. Oct 02 '12 at 03:56
  • CST is not always GMT-6, it can also be CDT which is GMT-5 – Ja͢ck Oct 02 '12 at 06:57

3 Answers3

1

This example checks the minutes every second, and updates the display time when the minutes change. It is not accurate before 2006, the last time DST was adjusted in the US.

<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>US Time Zones</title>
<style>
p{max-width:700px;font-size:1.25em}
</style>
<script>

Date.short_months= ['Jan', 'Feb', 'Mar', 'Apr', 'May',
'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
Date.tzones={
    N:['Newfoundland', -210],
    A:['Atlantic', -240],
    E:['Eastern', -300],
    C:['Central', -360],
    M:['Mountain', -420],
    P:['Pacific', -480],
    AK:['Alaska', -540],
    HA_:['Hawaii-Aleutian (Aleutian)', -600],
    HA:['Hawaii-Aleutian (Hawaii)', -600, -600]
};
Date.dstOff= function(d, tz){
    var off= tz[1], doff= tz[2],
    countstart, countend, dstart, dend,
    y= d.getUTCFullYear();
    if(y>2006 && off!== doff){
        countstart= 8, countend= 1,
        dstart= new Date(Date.UTC(y, 2, 8, 2)),
        dend= new Date(Date.UTC(y, 10, 1, 2));
        while(dstart.getUTCDay()!== 0){
            dstart.setUTCDate(++countstart);
        }
        while(dend.getUTCDay()!== 0){
            dend.setUTCDate(++countend);
        }
        dstart.setUTCMinutes(off);
        dend.setUTCMinutes(off);
        if(dstart<= d && dend>= d) off= doff;
    }
    return off;
}
Date.toTZString= function(d, tzp){
    d= d? new Date(d):new Date();
    tzp= tzp || 'G';
    var h, m, s, pm= 'pm', off, dst, str,
    label= tzp+'ST',
    tz= Date.tzones[tzp.toUpperCase()];
    if(!tz) tz= ['Greenwich', 0, 0];
    off= tz[1];
    if(off){
        if(tz[2]== undefined) tz[2]= tz[1]+60;
        dst= Date.dstOff(d, tz);
        if(dst!== off) label= tzp+'DT';
        d.setUTCMinutes(d.getUTCMinutes()+dst);
    }
    else label= 'GMT';
    h= d.getUTCHours();
    m= d.getUTCMinutes();
    if(h>12) h-= 12;
    else if(h!== 12) pm= 'am';
    if(h== 0) h= 12;
    if(m<10) m= '0'+m;
    var str= Date.short_months[d.getUTCMonth()]+' '+d.getUTCDate()+', ';
    return str+ h+':'+m+' '+pm+' '+label.replace('_', '').toUpperCase();
}
window.onload=function(){
    var who=document.getElementById('CentralTimer');
    who.firstChild.data= Date.toTZString('', 'C');
    Date.ctclock= setInterval(function(){
        var v=who.firstChild.data,
        t=Date.toTZString('', 'C');
        if(v!=t) who.firstChild.data=t;
    },1000);
who.ondblclick=function(){
    clearInterval(Date.ctclock);
    who.firstChild.data+=' (Clock Stopped)';
}
}
</script>
</head>
<body>
<h1 id="CentralTimer">Central Time</h1>


</body>
</html>
kennebec
  • 102,654
  • 32
  • 106
  • 127
0

The line everybody keeps referring to is

var offset = new Date().getTimezoneOffset();

This will set offset to a number, equal to the difference (in minutes) between the client's timezone and GMT. For CST, this should be 300 or 360, depending on daylight savings. The difference between the client's offset and the CST offset is the number of minutes you'll need to add/subtract from the date.

Date math is relatively straightforward:

var minutesToAdd = 300;  //can also be negative
var now = new Date();
now.setMinutes(now.getMinutes() + minutesToAdd);
//now is five hours ahead

Combined, these two pieces should do what you need.

smitelli
  • 6,835
  • 3
  • 31
  • 53
  • Note: You may want to test the `setMinutes()` bit on a range of browsers. There may be some incompatibilities with numbers outside of the 0-59 range. – smitelli Oct 02 '12 at 04:16
0

One way to do custom timezone'd clocks is to not use local time at all, but to always calculate from UTC after shifting the date by the time difference of your choice.

Here is your code modified to use .getUTC... and to move forwards for DST (using US rules from 2007)

function updateClock () {
    var d = null,                  // date
        h = 0, m = 0, s = 0,       // integers
        sh = '', sm = '', ss = '', // strings
        tod = 'AM',
        timeString = '',
        month = 0, dom = 0,        // used for DST calculation
        dos = 0, DST = false,
        offset = -21600000;        // -6 hours in ms

    d = new Date( (new Date()).valueOf() + offset ); // create date moved by offset

    h = d.getUTCHours(), m = d.getUTCMinutes(), s = d.getUTCSeconds();

    // --- calculate DST ---
    // needs to be modified for different regions ( currently US )
    // remove or comment out if you don't need DST

    month = d.getUTCMonth(), dom = d.getUTCDate(), dos = dom - d.getUTCDay();
    // dos is dom of most recent Sunday ( dos <= 0 means last month )
    if ( month === 2 ) {                    // March
        if ( dom > 14 ) DST = true;         // after second week, definately DST
        else if ( dos > 7 ) {               // Sunday was in second week
            if ( dom === dos ) {            // case for day of change
                if( h > 1 ) DST = true;
            } else DST = true;
        }
    } else if ( month === 10 ) {            // November
        if ( dom < 8 ) {                    // first week
            if ( dos < 1 ) DST = true;      // no Sunday yet, definately DST
            else if ( dos === dom &&        // case for day of change
                h < 1 ) DST = true;
        }
    } else if ( month > 2 && month < 10 )   // between March & November
        DST = true;                         // definately DST

    if ( DST ) {               // in DST
        h = h + 1;             // advance clock one hour
        if ( h === 24 ) h = 0; // allow for AM/PM check
    }

    // --- end of DST calculation ---

    ss = (s < 10 ? '0' : '') + s; // pad
    sm = (m < 10 ? '0' : '') + m; // pad

    if ( h >= 12 ) {   // convert to 12 hour
        tod = 'PM';
        h = h - 12;
    }
    if( h === 0 ) h = 12;
    sh = (h < 10 ? '0' : '') + h; // pad

    timeString = sh + ':' + sm + ':' + ss + ' ' + tod; // build final string

    document.getElementById("clock").firstChild.nodeValue = timeString;
    return timeString;
}
Paul S.
  • 64,864
  • 9
  • 122
  • 138