Rahul
Rahul

Reputation: 450

Convert UTC to EST by taking care of daylight saving

I want to convert UTC time to EST by taking care to daylight saving in PHP. This is what i did so far:

$from='UTC';
$to='EST';
$format='Y-m-d H:i:s';
$date=date('2106-03-15 23:00:00');// UTC time
date_default_timezone_set($from);
$newDatetime = strtotime($date);
date_default_timezone_set($to);
$newDatetime = date($format, $newDatetime);
date_default_timezone_set('UTC');
echo $newDatetime ;//EST time

It's returning 6:00 AM EST,but due to daylight saving It should be 7:00AM EST

Any Idea?

Upvotes: 5

Views: 10738

Answers (1)

Matt Raines
Matt Raines

Reputation: 4218

I think there are two faults here. One is that specifying Eastern Standard Time seems to mean daylight saving is ignored. The other is that you've typed 2106 when I think you meant 2016 and daylight saving time won't have started on 15 March 2106. The following appears to work:

$from='UTC';
$to='America/New_York';
$format='Y-m-d H:i:s';
$date=date('2016-03-15 23:00:00');// UTC time
date_default_timezone_set($from);
$newDatetime = strtotime($date);
date_default_timezone_set($to);
$newDatetime = date($format, $newDatetime);
date_default_timezone_set('UTC');
echo $newDatetime ;//EST time

On the other hand using the DateTime class is a bit easier to read, and this is very similar to the first example in the documentation for DateTime::setTimeZone()

$date = new DateTime('2016-03-15 23:00:00', new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format('Y-m-d H:i:s');

Upvotes: 17

Related Questions