Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda