skip to Main Content
<?php
$timezone='Asia/Tokyo';
$date_time_now = new DateTime('now', new DateTimeZone($timezone));
$date_time_now_formatted = $date_time_now->format('Y-m-d H:i:s');
               echo $date_time_now_formatted . '<br>';

$UTC = new DateTime('now', new DateTimeZone('UTC'));
$UTC_formatted = $UTC->format('Y-m-d H:i:s');
               echo $UTC_formatted . '<br>';

$difference_seconds = $date_time_now->getTimestamp() - $UTC->getTimestamp();
               echo $difference_seconds . ' <br>';
?>

Why do i get zero? I want to calculate time difference.

3

Answers


  1. Both of your dates are now, so they’re identical (you can get at most the tiny fraction of a second that it takes the computer to run both statements). In particular, DateTime::getTimestamp() returns the Unix time, which is an absolute time (a fixed moment in time). The whole DateTimeInterface implementation takes time zones into account, so switching a time to a different zone doesn’t make it a different (absolute) time.

    To calculate the difference between two local times, you can substract the timezone offsets:

    dump($UTC->getOffset(), $date_time_now->getOffset(), $UTC->getOffset() - $date_time_now->getOffset());
    
    Login or Signup to reply.
  2.  <?php
    $timezone_tokyo = new DateTimeZone('Asia/Tokyo');
    $timezone_utc = new DateTimeZone('UTC');
    
    $date_time_tokyo = new DateTime('now', $timezone_tokyo);
    $date_time_utc = new DateTime('now', $timezone_utc);
    
    $offset_tokyo = $timezone_tokyo->getOffset($date_time_tokyo);
    $offset_utc = $timezone_utc->getOffset($date_time_utc);
    
    $difference_seconds = $offset_tokyo - $offset_utc;
    echo "Time difference: " . $difference_seconds . ' seconds<br>';
    ?>
    

    Try this. here it gives difference in seconds

    Login or Signup to reply.
  3. $timezone='Asia/Tokyo';
    $date_time_now = new DateTime('now', new DateTimeZone($timezone));
    $date_time_now_formatted = $date_time_now->format('Y-m-d H:i:s');
    
    $UTC = new DateTime('now', new DateTimeZone('UTC'));
    $UTC_formatted = $UTC->format('Y-m-d H:i:s');
    
    $difference_seconds = strtotime($date_time_now_formatted) - 
    strtotime($UTC_formatted);
    
    return date('H:i:s', $difference_seconds); //or $different_seconds;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search