I AM...

    kellen_butler's photos More of kellen_butler's latest photos

    Determining when Daylight Saving Time starts in ends while programing

    7/27/2008 03:12:00 PM

    I recently ran into a situation where I was required to determine if a certain date was during DST or not. I looked around on Google for a bit trying to find anyone who has already done this, but most of the stuff I found did not work for me.

    I ended up writing my own code, and thought I would share it for the world. It is amazingly simple, but caused me to think a bit before I got to it.

    Keep in mind that I am not a computer science major, nor do I claim to be great at programming. If you have any suggestions on a more efficient way of determining this, please let me know.

    //Kellen Butler

    //July 27, 2008

    //Find the day in which DST starts or ends.

    //Code can be modified to find any situation where you are looking for a date for the "Second Tuesday of the month" situation.

    //This code sample will work for DST End as well, it just needs to have its variables adjusted.

    //Written for PHP

    function dststart($year){
        //Daylight Savings Time starts on the second Sunday in March.
        //So $day = 0; for Sunday
        //$month = 3; for March
        //$week = 2; for the "second" (Sunday in March)
        $dayofweek = 0;
        $month = 3;
        $week = 2;


        //The following determines what day of week the ith day of the month is.
        //Once the first $dayofweek desired is found, the for loop will end.
        for($i=1, $dow=999; $dow != $dayofweek; $i++){
            $dow = date(w, mktime(0,0,0,$month,$i,$year));
            }


        $i--; //adjusts  for extra increment not desired

        $date = ($i + 7*($week-1)); //$date is that day of month that DST starts in. For 2008 this would return 9
        return $date;
        }

    1 comments

    1 Comments:

    Don't use Predefined variables names and follow variable naming conventions!! :-) Otherwise, cool.
    By Anonymous Mike, at July 27, 2008 10:27 PM   Post a Comment