note 81753 deleted from function.strtotime by derick
| From: | derick@php.net | Date: | Sun, 03 Aug 2008 11:54:52 +0000 |
| Subject: | note 81753 deleted from function.strtotime by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-143114@lists.php.net to get a copy of this message | ||
Note Submitter: timhavens at gmail dot com
----
I needed a function to return all the dates between two dates. I've looked for something like
this in the past an didn't find it. I'm sure there are better ways, but I wanted to post
this in case it was helpful to others.
<?php
function dates_between_dates($date1,$date2) {
$return_array = array();
$num_days = date_diff('d',$date1,$date2)+1;
for($i=0;$i<=$num_days;$i++) {
$return_array[] = date('Y-m-d',strtotime($date1."+$i day"));
}
return $return_array;
}
function date_diff($interval, $date1, $date2)
{
//convert the dates into timestamps
$date1 = strtotime($date1);
$date2 = strtotime($date2);
$seconds = $date2 - $date1;
if ($seconds < 0)
{
$tmp = $date1;
$date1 = $date2;
$date2 = $tmp;
$seconds = 0-$seconds;
}
//reconvert the timestamps into dates
if ($interval =='y' || $interval=='m') {
$date1 = date("Y-m-d h:i:s", $date1);
$date2= date("Y-m-d h:i:s", $date2);
}
switch($interval) {
case "y":
list($year1, $month1, $day1) = split('-', $date1);
list($year2, $month2, $day2) = split('-', $date2);
$time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) +
(date('s',$date1)
);
$time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) +
(date('s',$date2)
);
$diff = $year2 - $year1;
if($month1 > $month2) {
$diff -= 1;
} elseif($month1 == $month2) {
if($day1 > $day2) {
$diff -= 1;
} elseif($day1 == $day2) {
if($time1 > $time2) {
$diff -= 1;
}
}
}
break;
case "m":
list($year1, $month1, $day1) = split('-', $date1);
list($year2, $month2, $day2) = split('-',$date2);
$time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) +
(date('s',$date1)
);
$time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) +
(date('s',$date2)
);
$diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1);
if($day1 > $day2) {
$diff -= 1;
} elseif($day1 == $day2) {
if($time1 > $time2) {
$diff -= 1;
}
}
break;
case "w":
// Only simple seconds calculation needed from here on
$diff = floor($seconds / 604800);
break;
case "d":
$diff = floor($seconds / 86400);
break;
case "h":
$diff = floor($seconds / 3600);
break;
case "i":
$diff = floor($seconds / 60);
break;
case "s":
$diff = $seconds;
break;
}
return $diff;
}
?>