简体   繁体   中英

comparing dates in php

In the following php code, I am trying to show only those products from products.xml file that are stored in the last month. But my code does not work. Please help me in getting correct output. I also need to show products that are stored in the last 24 hours and last week.

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

Strtotime is nicer than you might think. For instance, this code;

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

Will currently output "true" - because last month is 09, and this month is 10.

But what if this month is 01, and last month is 12? Then it would be false. I'd recommend you compare on years as well.

Edit: If this isn't a problem, and you only want to evaluate this for the most recent additions, then that should be fine. But you'll run into problems the year after if you only compare from last month, unless your import data only contains stuff from this year.

try

 $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,
    );
   }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM