Compare two dates with PHP

2

I would like to compare two dates, but not only with the year, month and day information, also with the time.

I'm trying with:

$datetime1 = date_create('2009-10-11 19:10');
$datetime2 = date_create('2009-10-13 18:23');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a días');

It returns only the result in days, not the hours. Is there a way to tell me the difference in days and hours?

    
asked by JetLagFox 26.03.2017 в 17:30
source

3 answers

4

The method format() uses different modifiers that allow the text to be replaced in them depending on the value you indicate them.

What does this mean?

On the line where you do:

echo $interval->format('%R%a días');

You are making the function format replace % R and _% a% with the following values (according to the PHP Documentation ) :

  

R Sign "-" when it is negative, "+" when it is positive

     

a Total number of days as a result of an operation with DateTime :: diff (), or otherwise (unknown)

What is missing in the format are the modifiers, which will return the difference in hours, minutes and seconds, (according to PHP Documentation ) :

  

H Hours, numeric, at least 2 digits starting with 0

     

I Minutes, numeric, at least 2 digits starting with 0

     

S Seconds, numeric, at least 2 digits starting with 0

Leaving your code like this:

<?php

$datetime1 = date_create('2009-10-11 19:10:01');
$datetime2 = date_create('2009-10-13 20:11:05');
$interval = date_diff($datetime1, $datetime2);

echo $interval->format('%R%a días %H horas %I minutos %S segundos');

?>

Result

  

+2 days 01 hours 01 minutes 04 seconds

    
answered by 26.03.2017 / 17:39
source
1

Actually variable $interval is an array in which the difference is stored in years, months, days, hours, etc ...

You can see all the data that is stored inside that variable using:

var_dump($interval);

However, if you only want to make the difference in days and hours, you can simply show those two values on the screen in the following way:

echo($interval->d . " dias");
echo($interval->h . " horas");

I'll leave you the demo so you can see the result.

    
answered by 26.03.2017 в 17:38
0

If you only want to compare the dates without the need to know what the difference is in days, hours, minutes and seconds, a comparison of dateTime can be useful:

$datetime1 = date_create('2009-10-11 19:10');
$datetime2 = date_create('2009-10-11 19:23');

if($datetime1 < $datetime2) {
    echo $datetime1->format('d-m-Y H:i:s')." es menor que ".$datetime2->format('d-m-Y H:i:s')."<br>";

} else if($datetime1 == $datetime2) {
    echo $datetime1->format('d-m-Y H:i:s')." es igual que ".$datetime2->format('d-m-Y H:i:s');

} else {
    echo $datetime1->format('d-m-Y H:i:s')." es mayor que ".$datetime2->format('d-m-Y H:i:s');
}
    
answered by 26.03.2017 в 17:53