Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda