1

Possible Duplicate:
php date compare
PHP compare dates

I have this code which permits me to grab today's date in this format:

 $today = date("d-m-Y");  

Then this query:

while ($row1 = mysql_fetch_array($queryenddate)) { 
$end_date=$row1['end_date'];
}

The end date prints something like : 12-02-2012

How can i compare this two dates? What do i need to do? Thanks

Community
  • 1
  • 1
Tao
  • 85
  • 3
  • 7

3 Answers3

6

You can just use DateTime

$today = new DateTime();
$date = DateTime::createFromFormat("d-m-Y", $end_date);

if ($today > $date) {
    // Totaay is more current
}

if ($today->format("m") == $date->format("m")) {
    // they have same month
}

You can also do something like this

$diffrence = $today->diff($date); //enddate is "01-01-2010"
var_dump($diffrence);

Output

object(DateInterval)[3]
  public 'y' => int 2
  public 'm' => int 8
  public 'd' => int 24
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'invert' => int 1
  public 'days' => int 998
Baba
  • 94,024
  • 28
  • 166
  • 217
  • hey thanks. if i use it like you said, it says: Object of class DateTime could not be converted to string – Tao Sep 25 '12 at 15:49
  • @Tao see demo : http://codepad.viper-7.com/EnIq8B what is your version of PHP ??? – Baba Sep 25 '12 at 15:51
  • Hey thanks :) i'll take a look at it, i'm on localhost, have no idea... but thanks! – Tao Sep 25 '12 at 15:53
6

you can compare this by

if(strtotime($date1)>strtotime($date2))
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
1

You can use the strtotime () function to convert a date into a number, then you can use for comparisons or opereaciones.

 $today = date("d-m-Y"); 

 $end_date='02-09-2012';

 echo $today;
 echo "<br>".$end_date;

 $diference= (strtotime($end_date)-strtotime($today))/86400;
 $diference= abs($diference); 
 $diference= floor($diference);

  echo "<br>".$diference;
Edy Aguirre
  • 2,113
  • 20
  • 20
  • Yes, the problem is that this one calculates the day.. i need a whole calculation, month year included – Tao Sep 25 '12 at 16:06