Home > Back-end >  php date difference calculation adding additional days
php date difference calculation adding additional days

Time:02-28

Trying to display difference between two dates in PHP.

<?php
    $date1 = new DateTime("2022-03-01");
    $date2 = new DateTime("2022-04-01");
    $interval = $date1->diff($date2);
    echo $interval->days;
    echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 
?>

I am getting result as:-

31difference 0 years, 1 months, 3 days

$interval->days result is correct, but why having $interval->d as 3 when its just a month difference?

CodePudding user response:

Try below

<?php
    $date1 =DateTime::createFromFormat("Y-m-d", "2022-03-01");
    $date2 =DateTime::createFromFormat("Y-m-d", "2022-04-01");
    $interval = $date1->diff($date2);
    echo $interval->days;
    echo " \ndifference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 
?>

CodePudding user response:

It looks like a bug, that depends on the timezone and hour.

With UTC timezone, it is OK :

$date1 = new DateTime("2022-03-01 00:00", new DateTimeZone("UTC"));
$date2 = new DateTime("2022-04-01 00:00", new DateTimeZone("UTC"));

difference 0 years, 1 months, 0 days

With Europe/Berlin timezone at midnight, we have the 3 days offset :

$date1 = new DateTime("2022-03-01 00:00", new DateTimeZone("Europe/Berlin"));
$date2 = new DateTime("2022-04-01 00:00", new DateTimeZone("Europe/Berlin"));

difference 0 years, 1 months, 3 days

At 01:00 in the morning, it is kind of OK : 0 month but 31 days

$date1 = new DateTime("2022-03-01 01:00", new DateTimeZone("Europe/Berlin"));
$date2 = new DateTime("2022-04-01 01:00", new DateTimeZone("Europe/Berlin"));

0 years, 0 months, 31 days

At 12:00, everything is right again: 1 month

$date1 = new DateTime("2022-03-01 12:00", new DateTimeZone("Europe/Berlin"));
$date2 = new DateTime("2022-04-01 12:00", new DateTimeZone("Europe/Berlin"));

0 years, 1 months, 0 days

  • Related