Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates in php [duplicate]

Tags:

php

People also ask

How to compare 2 dates PHP?

Once you have created your DateTime objects, you can also call the diff() method on one object and pass it the other date in order to calculate the difference between the dates. This will give you back a DateInterval object. $last = new DateTime( "25 Dec 2020" ); $now = new DateTime( "now" );

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


You will have to make sure that your dates are valid date objects.

Try this:

$date1=date('d/m/y');
$tempArr=explode('_', '31_12_11');
$date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));

You can then perform the strtotime() method to get the difference.


Using DateTime::createFromFormat:

$format = "d_m_y";
$date1  = \DateTime::createFromFormat($format, "03_01_12");
$date2  = \DateTime::createFromFormat($format, "31_12_11");

var_dump($date1 > $date2);

Not answering the OPs actual problem, but answering just the title. Since this is the top result for "comparing dates in php".

Pretty simple to use Datetime Objects (php >= 5.3.0) and Compare them directly

$date1 = new DateTime("2009-10-11");
$date2 = new DateTime("tomorrow"); // Can use date/string just like strtotime.
var_dump($date1 < $date2);

The date_diff() function returns the difference between two DateTime objects.

If the first date is before the second date a positive number of days will be returned; otherwise a negative number of days:

<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>

output will be "+272 days" ;

changing $date1 = "2014-03-15"

 <?php
    $date1=date_create("2014-03-15");
    $date2=date_create("2013-12-12");
    $diff=date_diff($date1,$date2);
    echo $diff->format("%R%a days");
    ?>

Output will be "-93 days"


<?php
       $expiry_date = "2017-12-31 00:00:00"
       $today = date('d-m-Y',time()); 
       $exp = date('d-m-Y',strtotime($expiry_date));
       $expDate =  date_create($exp);
       $todayDate = date_create($today);
       $diff =  date_diff($todayDate, $expDate);
       if($diff->format("%R%a")>0){
             echo "active";
       }else{
           echo "inactive";
       }
       echo "Remaining Days ".$diff->format("%R%a days");
?>