0

我有一个结构如下的数组:

Array ( [0] => 24-12-2013 [1] => 25-12-2013 [2] => 26-12-2014 [3] => 27-12-2013 [4])

我想检查数组中的任何日期是否在给定的日期范围内。

日期范围的结构如下:

$start = (date("d-m-Y", strtotime('25-12-2013')));
$end =   (date("d-m-Y", strtotime('26'12'2013')));

我想知道数组中的哪些日期在日期范围内。

4

6 回答 6

8

几件事:

  • 使用时间戳或DateTime对象来比较日期,而不是字符串
  • 使用日期格式 YYYY-MM-DD 以避免您的日期格式(d/m/y 或 m/d/y)的潜在歧义

此代码将执行您想要的操作:

$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";
    }
}

看看它的实际效果:

http://3v4l.org/GWJI2

于 2013-11-13T15:58:07.497 回答
3
$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); 
        }
    )
);
于 2013-11-13T16:02:24.317 回答
2
<?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);

看到它在行动

于 2013-11-13T15:57:27.620 回答
0
$_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>';
于 2013-11-13T15:57:49.510 回答
0

遍历数组,将每个日期转换为 unix 时间(自 1970 年 1 月 1 日以来的秒数),并进行简单的数学运算以查看秒数是否在范围之间。像这样:

$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
 }
于 2013-11-13T15:57:59.623 回答
0
// 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));
});
于 2013-11-13T16:11:52.217 回答