M.I.T.
M.I.T.

Reputation: 1042

Compare date with date list in PHP

I have a date list like:

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

I want to compare date list with today date. From that I want a list of dates which have already past. Also, I want a list of dates which are in the Future.

Upvotes: 0

Views: 7313

Answers (4)

deex
deex

Reputation: 515

You can use strtotime() to convert your dates to UNIX timestamp then perform a simple greater/less than test. Do something like this:

<?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;
?>

Upvotes: 1

Vytautas
Vytautas

Reputation: 3539

Try http://www.php.net/manual/en/datetime.diff.php

From manual:

Object oriented style

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

Procedural style

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

The above examples will output:

+2 days

Also maybe you will find usefull.

Example #2 DateTime object comparison

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);
?>

The above example will output:

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

Upvotes: 0

J A
J A

Reputation: 1766

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

Upvotes: 0

BeRecursive
BeRecursive

Reputation: 6366

Use PHP's strtotime() method:

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

Upvotes: 0

Related Questions