Server Environment
Redhat Enterprise Linux
PHP 5.3.5
Problem
Let's say I have a UTC date and time such as 2011-04-27 02:45 and I want to convert it to my local time, which is America/New_York.
Three questions:
1.) My code below might solve the problem, would you agree?
<?php
date_default_timezone_set('America/New_York'); // Set timezone.
$utc_ts = strtotime("2011-04-27 02:45"); // UTC Unix timestamp.
// Timezone offset in seconds. The offset for timezones west of UTC is always negative,
// and for those east of UTC is always positive.
$offset = date("Z");
$local_ts = $utc_ts + $offset; // Local Unix timestamp. Add because $offset is negative.
$local_time = date("Y-m-d g:i A", $local_ts); // Local time as yyyy-mm-dd h:m am/pm.
echo $local_time; // 2011-04-26 10:45 PM
?>
2.) But, does the value of $offset automatically adjust for Daylight Savings Time (DST) ?
3.) If not, how should I tweak my code to automatically adjust for DST ?
Thank you :-)
This will do what you want using PHPs native DateTime and DateTimeZone classes:
$utc_date = DateTime::createFromFormat(
'Y-m-d G:i',
'2011-04-27 02:45',
new DateTimeZone('UTC')
);
$nyc_date = $utc_date;
$nyc_date->setTimeZone(new DateTimeZone('America/New_York'));
echo $nyc_date->format('Y-m-d g:i A'); // output: 2011-04-26 10:45 PM
See DateTime::createFromFormat man page for more information.
After some experimentation between time zones that do and do not currently have DST I have discovered that this will take DST into account. The same conversion using my method above renders the same resulting time.