Search code examples
phpdatetimetimercountdown

PHP countdown timer show hours wrong


I am creating a simple timer which takes difference from two dates and outputs it like: 20 days 5 hours 23 minutes. Everything is working okay, when the difference is not biger than month, but when i try big difference, days and minutes show okay, but hour is always +1 hour. How to fix that?

function countdownTimer($targetTime) {
  $targetTime = DateTime::createFromFormat('Y-m-d H:i:s',$targetTime);
  $currentTime = new DateTime();
  $timeDifference = $targetTime->diff($currentTime);

  return $timeDifference->format("%a days %H hours %i minutes");    
}

Solution

  • Probably because PHP is accounting for daylight savings and it's coming up to that time of year. I tried your code, everything seems fine:

    function countdownTimer($targetTime) {
      $targetTime = DateTime::createFromFormat('Y-m-d H:i:s',$targetTime);
      $currentTime = new DateTime();
      $timeDifference = $targetTime->diff($currentTime);
    
      return $timeDifference->format("%a days %H hours %i minutes");    
    }
    
    $targetTime = date_create("@".time())->add(date_interval_create_from_date_string("+1 month"))->format('Y-m-d H:i:s');
    
    var_dump(countdownTimer($targetTime));