比较日期PHP

时间:2014-04-14 08:57:09

标签: php

我想只显示当月的结果,但我不知道怎么做,我目前的输出是这样的。

输出

2014-04-11
-> array
2014-04-11 
2014-04-05
2014-03-29

PHP

$date = date('Y-m-d');

echo $date;

echo "<pre>";
foreach ($submissions as $test){
    if($date >=  substr($test['thing']['created'], 0, 10)){
        echo substr($test['thing']['created'], 0, 10);
        echo "<br>";
    }
}
echo "</pre>";

我目前的代码不会作为唯一检查整个数字是否大于或等于任何人的想法?

5 个答案:

答案 0 :(得分:2)

试试strtotime

$year  = date('Y');
$month = date('m');

foreach ($submissions as $test) {
  $timestamp = strtotime($test['thing']['created']);
  $testYear  = date('Y', $timestamp);
  $testMonth = date('m', $timestamp);

  if (($month >= $testMonth && $year == $testYear) || $year > $testYear) {
    // test passed
  }
}

答案 1 :(得分:1)

如果您的问题只是当月的结果:

$date = date('Y-m');
echo "<pre>";
foreach ($submissions as $test){
    // if month & year is equal
    if($date == substr($test['thing']['created'], 0, 7)){
        echo substr($test['thing']['created'], 0, 10);
        echo "<br>";
    }
}
echo "</pre>";

如果要对其进行排序,则必须转换为时间戳

答案 2 :(得分:0)

我不是php的专家,但请看一下:http://fr2.php.net/manual/fr/function.date.php

日期('m')会解决您的问题吗?

答案 3 :(得分:0)

您可以尝试两种方式:

  • 将它们转换为时间戳,然后比较int
  • 如果您正在查询数据库,ORDER BY日期中的日期

答案 4 :(得分:0)

当前月份的变量$cur_m=date('m')

使用-循环爆炸变量。

$p = explode('-',$test['thing']['created']);

循环检查当前月份,如下所示

if($p[1]==$cur_m){ your code... }