比较PHP问题中的日期

时间:2014-01-31 00:37:16

标签: php date

我在PHP中有一个数组,其日期格式如下:d / m / yyyy:

["01/02/2014","02/02/2014","03/02/2014","04/02/2014","05/02/2014","06/02/2014","07/02/2014","08/02/2014","09/02/2014","10/02/2014"]

有没有办法在日期进行计算,只打印"03/02/2014"之后和"08/02/2014"日期之前的日期:

"04/02/2014","05/02/2014","06/02/2014","07/02/2014"

由于

3 个答案:

答案 0 :(得分:1)

$dates = ["01/02/2014","02/02/2014","03/02/2014","04/02/2014","05/02/2014","06/02/2014","07/02/2014","08/02/2014","09/02/2014","10/02/2014"];

$first = DateTime::createFromFormat("m/d/Y", '03/02/2014');
$last  = DateTime::createFromFormat("m/d/Y", '08/02/2014');
foreach ($dates as $date) {
    if ($date > $first && $date < $last) {
        // you're good
    }
}

答案 1 :(得分:1)

您可以使用DateTime课程和array_filter()

$dates = ["01/02/2014","02/02/2014","03/02/2014","04/02/2014","05/02/2014","06/02/2014","07/02/2014","08/02/2014","09/02/2014","10/02/2014"];

$min = new DateTime('2014-03-02');
$max = new DateTime('2014-08-02');

$dates = array_filter($dates, function ($date) use ($min, $max) {
    $dt = new DateTime($date);

    return $dt >= $min && $dt <= $max;
});

答案 2 :(得分:0)

您可以使用array_filter功能。像

这样的东西
<?php

$arr = [
  "01/02/2014",
  "02/02/2014",
  "03/02/2014",
  "04/02/2014",
  "05/02/2014",
  "06/02/2014",
  "07/02/2014",
  "08/02/2014",
  "09/02/2014",
  "10/02/2014"
];

$cmp = strtotime("08/02/2014");

$arr = array_filter($arr, function ($date) use ($cmp) {
  return strtotime($date) < $cmp;
});

print_r($arr);

参考