Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
php date difference calculation adding additional days

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 "; 
?>
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!