Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Snippets by user Michael Smith Snippets by user Michael Smith

Get the dates between two dates

Sometimes you need a list of the dates between two dates.

    /**
     * Returns an array with the dates between to dates given.
     *
     * @link http://us3.php.net/manual/en/function.date.php#AEN25217
     * 
     * @param mixed $startdate Timestamp or strtotime() recognizeable string
     * @param mixed $enddate Timestamp or strtotime() recognizeable string
     * @param string[optional] $format date() format string
     * @return mixed Array of timestamps or dates if given format
     */
    public static function dates_between($startdate, $enddate, $format=null){
 
        (is_int($startdate)) ? 1 : $startdate = strtotime($startdate);
        (is_int($enddate)) ? 1 : $enddate = strtotime($enddate);
 
        if($startdate > $enddate){
            return false; //The end date is before start date
        }
 
        while($startdate < $enddate){
            $arr[] = ($format) ? date($format, $startdate) : $startdate;
            $startdate += 86400;
        }
        $arr[] = ($format) ? date($format, $enddate) : $enddate;
 
        return $arr;
    }

You can give it a timestamp or a string date. It will use date() to format the output if given a $format.

by Michael Smith on 2006-06-16, tagged date 
(1 comment)