Compare dates in php


Why this example does not work for me:

$fecha = new \DateTime("2016-05-17 0:0:0");
$fechaCounter = clone $fecha;
$fechaLimite = clone $fecha;

while ($fechaCounter <= $fechaLimite->add(new \DateInterval("P2D"))) {
    echo "hola mundo";
    $fechaCounter->add(new \DateInterval("P1D"));

Instead of printing 2 times hello the world causes an infinite loop.

Thank you in advance. Greetings


So if it works:

$fecha = new \DateTime("2016-05-17 0:0:0");
$fechaCounter = clone $fecha;
$fechaLimite = clone $fecha;
$fechaLimite->add(new \DateInterval("P2D"));
echo $fechaLimite->format("d-m-Y H:i:s");
while ($fechaCounter <= $fechaLimite) {
    echo $fechaCounter->format("d-m-Y H:i:s")."\n";
    $fechaCounter->add(new \DateInterval("P1D"));
asked by Red 15.05.2016 в 15:19

2 answers


Is that when executing

$fechaLimite->add(new \DateInterval("P2D"))

It is modified each time $fechaLimite . If we look at the manual we see that add modifies the object Date : link

You have to be careful in each function or object to know if the functions treat the objects as mutable or immutable (that is, if they modify them or not). That changes for each language.

answered by 15.05.2016 в 16:09

Try this code using DateTime :: diff :

View Demo

$fechaHoy = new DateTime("2016-05-17 00:00:00");
$fechaLimite = clone $fechaHoy;    
$fechaLimite->add(new DateInterval("P2D"));

// Calcula la diferencia y devuelve el resultado
echo = $fechaHoy->diff($fechaLimite)->format('%a'); // 2
answered by 15.05.2016 в 16:22