jcadima
4/9/2016 - 5:30 PM

Working with Time Zones - the right way

Working with Time Zones - the right way

<?php
// convert from UTC to the local TimeZone for output 
// then convert from the local time zone to UTC on input
$utcDateTime = new DateTime('2014-08-24 13:14', new DateTimeZone('UTC') ) ;

$localDateTime = clone $utcDateTime;

$localDateTime->setTimeZone(new DateTimeZone('America/New_York') ) ;

?>

<p>The UTC date/time is: <?php echo $utcDateTime->format("Y-m-d H:i:s")  ?> </p>

<p>The New York date/time is: <?php echo $localDateTime->format("Y-m-d H:i:s") ?></p>

Output:

The UTC date/time is: 2014-08-24 13:14:00
The New York date/time is: 2014-08-24 09:14:00


<?php  // method 2 
// all dates stored in a database is UTC
// all users should have a timezone attached to their own account
// $publishDate = $_POST['publish_date'] ;  // this would come from POST superglobal

$publishDate = '2014-08-24';

$localDateTime = new DateTime($publishDate, new DateTimeZone('America/New_York') ) ;

$utcDateTime = clone $localDateTime;

$utcDateTime->setTimeZone(new DateTimeZone('UTC') ) ;
?>

<p>The UTC date/time is: <?php echo $utcDateTime->format("Y-m-d H:i:s")?></p>
<p>The New York date/time is: <?php $localDateTime->format("Y-m-d H:i:s") ?></p>

Output:

The UTC date/time is: 2014-08-24 13:14:00
The New York date/time is: 2014-08-24 09:14:00