php check multiple dates in array are within a date range

半腔热情 提交于 2019-12-01 14:14:12

Couple things:

  • Use timestamps or DateTime objects to compare dates, not strings
  • Use date format YYYY-MM-DD to avoid potential ambiguity about your date format (d/m/y or m/d/y)

This code will do what you want:

$dates = array("2013-12-24","2013-12-25","2014-12-24","2013-12-27");
$start = strtotime('2013-12-25');
$end =   strtotime('2013-12-26');

foreach($dates AS $date) {
    $timestamp = strtotime($date);
    if($timestamp >= $start && $timestamp <= $end) {
        echo "The date $date is within our date range\n";
    } else {
        echo "The date $date is NOT within our date range\n";
    }
}

See it in action:

http://3v4l.org/GWJI2

$dates = array ('24-12-2013', '25-12-2013', '26-12-2014', '27-12-2013');

$start = strtotime('25-12-2013');
$end =   strtotime('26-12-2013');

$inDateRange = count(
    array_filter(
        $dates,
        function($value) use($start, $end) {
            $value = strtotime($value);
            return ($value >= $start && $value <= $end); 
        }
    )
);
<?php
$start   = DateTime::createFromFormat('d-m-Y', '25-12-2013');
$end     = DateTime::createFromFormat('d-m-Y', '26-12-2013');
$dates   = array('24-12-2013','25-12-2013','26-12-2014','27-12-2013');
$matches = array();
foreach ($dates as $date) {
    $date2 = DateTime::createFromFormat('d-m-Y', $date);
    if ($date2 >= $start && $date2 =< $end) {
        $matches[] = $date;
    }
}
print_r($matches);

See it in action

$_between = array();
$start = date('Ymd', strtotime($start));
$end = date('Ymd', strtotime($end));

foreach ($dates as $date)
{
   $date = date('Ymd',strtotime($date));
   if ($date > $start && $date < $end) {
       array_push($_between,$date);
       continue;
   }
}
echo '<pre>';
var_dump($_between);
echo '</pre>';

Loop over the array turning each date into unix time (seconds since Jan 1, 1970), and do simple math to see if the number of seconds is between the range. Like so:

$start = strtotime('25-12-2013');
$end =   strtotime('26'12'2013');

foreach($date in $dates) {
    $unix_time = strtotime($date);
    if($unix_time > $start && $unix_time < $end)
        //in range
 }
// PHP >= 5.3:

$dates_in_range = array_filter($array, function($date) {
    global $start;
    global $end;
    return (strtotime($date) >= strtotime($start) and strtotime($date) <= strtotime($end));
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!