在php中比较日期

时间:2012-10-23 11:27:37

标签: php

在下面的php代码中,我试图仅显示上个月存储的products.xml文件中的那些产品。但我的代码不起作用。请帮助我获得正确的输出。我还需要显示过去24小时和上周存储的产品。

$current_month = date("m");
$last_month = date('m', strtotime(date('-m')." -1 month"));

$xml = simplexml_load_file("products.xml");

$products = array();
foreach ($xml->product as $product) {
   if ($product->date('m') == $last_month) {
      $products[] = array( 'name' => (string)$product->name,
                           'details' => (string)$video->details );
   }    
}

2 个答案:

答案 0 :(得分:0)

Strtotime比你想象的要好。例如,这段代码;

if (date('m') > date('m', strtotime('last month')))
    echo true;
else
    echo false;

目前输出“true” - 因为上个月是09,本月是10。

但是如果这个月是01,上个月是12呢?那就错了。我建议你也要多年来比较。

编辑:如果这不是问题,并且您只想对最近添加的内容进行评估,那么这应该没问题。但是如果你只是比较上个月,你会遇到问题,除非你的导入数据只包含今年的东西。

答案 1 :(得分:0)

 $last_month = date('m', strtotime("-1 month"));

 $xml = simplexml_load_file("products.xml");

$products = array();
foreach ($xml->product as $product)
 {
  if ($product->date('m') == $last_month)
   {
$products[] = array(
'name'=>(string)$product->name,
'details'=>(string)$video->details,
    );
   }    
}