将日期与PHP中的日期列表进行比较

时间:2012-04-26 11:27:07

标签: php magento

我有一个日期列表,如:

2012-04-11
2012-04-29
2012-04-26
2012-04-23
2012-03-21
2012-07-23
2012-12-19

我想将日期列表与今天的日期进行比较。从那里我想要一个已经过去的日期列表。另外,我想要一份未来的日期列表。

4 个答案:

答案 0 :(得分:1)

您可以使用strtotime()将日期转换为UNIX时间戳,然后执行简单的大于/小于测试。做这样的事情:

<?php
$past_dates = array();
$future_dates = array();
$dates = array('2012-04-11', '2012-04-29', '2012-04-26', '2012-04-23', '2012-03-21', '2012-07-23', '2012-12-19');
$today = date('Y-m-d');
foreach($dates as $value) {
  if(strtotime($value) < strtotime($today)) {
    $past_dates[] = $value;
  } else if(strtotime($value) > strtotime($today)) {
     $future_dates[] = $value;
  }
}
echo 'Past dates:';
echo '<pre>';
print_r($past_dates);
echo 'Future dates:';
echo '<pre>';
print_r($future_dates);
echo '</pre>';
echo 'Today is: ' . $today;
?>

答案 1 :(得分:0)

使用PHP的strtotime()方法:

$date = "2012-04-29"; 
$todays_date = date("Y-m-d"); 
$today = strtotime($todays_date); 
$test_date = strtotime($date); 

if ($test_date > $today) { 
    // Some Code
} 
else { 
    // Some code
} 

答案 2 :(得分:0)

$dateArray =   array('2012-04-11','2012-04-29','2012-04-26','2012-04-23','2012-03-21','2012-07-23','2012-12-19')
$pastDates = array();
$futureDates = array();

foreach ($dateArray as $date){
  $dateTime = strtotime($date);
  if (time() > $dateTime){
     $pastDates[] = $date;
  } else {
     $futureDates[] = $date;
  }
}

答案 3 :(得分:0)

尝试http://www.php.net/manual/en/datetime.diff.php

来自手册:

面向对象的风格

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

程序风格

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

以上示例将输出:

+2 days

也许你会发现有用的。

  

示例#2 DateTime对象比较

Note:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.
<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>

以上示例将输出:

bool(false)
bool(true)
bool(false)