Find the different between two time zone in PHP

Description

The following code shows how to find the different between two time zone.

Example


<?php/*  w w w  . j a v  a 2s  . c  om*/

$timezone1 = 'America/New_York';
$timezone2 = 'America/Los_Angeles';

$tzObj1 = new DateTimeZone($timezone1);
$tzObj2 = new DateTimeZone($timezone2);


$now = new DateTime('now', $tzObj1);

$offset1 = $tzObj1->getOffset($now);
$offset2 = $tzObj2->getOffset($now);
$diff = $offset1 - $offset2;
if ($diff == 0) {
  echo 'Both cities are in the same time zone';
} else {
  $hours = floor(abs($diff)/60/60);
  $minutes = ((abs($diff)%3600)/60);
  $gap = "$hours hour(s) $minutes minutes";
  $whichWay = ($offset1 > $offset2) ? 'ahead of' : 'behind';
  echo "<p>$timezone1 is $gap $whichWay $timezone2.</p>";
} 
$otherTime = new DateTime('now', $tzObj2);
echo "<p>The time in $timezone1 is " . $now->format('g:i A');
echo ", and in $timezone2, it's " . $otherTime->format('g:i A') . '</p>';
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone