Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt

Q281 How can I tell when Daylight Saving is in effect?

You are here: irt.org | FAQ | JavaScript | Date | Q281 [ previous next ]

The trick is knowing when the clocks change. Its not the same weekend everywhere.

A couple of facts:

If someone can provide me with details of other rules for other places in the world I would be most grateful.

We can then use JavaScript to calculate the actual dates for any one year. Once we've got the start and end dates, we just need to check if the date today falls within the two dates, and if so adjust the clock by an hour. Heres the code for it:

<SCRIPT LANGUAGE="JavaScript"><!--
function makeArray()    {
    this[0] = makeArray.arguments.length;
    for (i = 0; i<makeArray.arguments.length; i++)
        this[i+1] = makeArray.arguments[i];
}

var daysofmonth   = new makeArray( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysofmonthLY = new makeArray( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

function LeapYear(year) {
    if ((year/4)   != Math.floor(year/4))   return false;
    if ((year/100) != Math.floor(year/100)) return true;
    if ((year/400) != Math.floor(year/400)) return false;
    return true;
}

function NthDay(nth,weekday,month,year) {
    if (nth > 0) return (nth-1)*7 + 1 + (7 + weekday -
DayOfWeek((nth-1)*7 + 1,month,year))%7;
    if (LeapYear(year)) var days = daysofmonthLY[month];
    else                var days = daysofmonth[month];
    return days - (DayOfWeek(days,month,year) - weekday + 7)%7;
}

function DayOfWeek(day,month,year) {
    var a = Math.floor((14 - month)/12);
    var y = year - a;
    var m = month + 12*a - 2;
    var d = (day + y + Math.floor(y/4) - Math.floor(y/100) +
Math.floor(y/400) + Math.floor((31*m)/12)) % 7;
    return d+1;
}

function y2k(number)    { return (number < 1000) ? number + 1900 : number; }

var today = new Date();
var year = y2k(today.getYear());

var DSTstart = new Date(year,4-1,NthDay(1,1,4,year),2,0,0);
var DSTend   = new Date(year,10-1,NthDay(-1,1,10,year),2,0,0);

function getMS(date) {
    return
Date.UTC(y2k(date.getYear()),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds())
}

var todayMS = getMS(today);
var DSTstartMS = getMS(DSTstart);
var DSTendMS = getMS(DSTend);

if (todayMS > DSTstartMS && todayMS < DSTendMS)
    document.write('Daylight Saving within effect');
else
    document.write('Daylght Saving NOT within effect');
//--></SCRIPT>

Feedback on 'Q281 How can I tell when Daylight Saving is in effect?'

©2013 Martin Webb