Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTC to EST by taking care of daylight saving

Tags:

php

datetime

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?

like image 925
Rahul Avatar asked Dec 11 '22 17:12

Rahul


1 Answers

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');
like image 191
Matt Raines Avatar answered Dec 15 '22 00:12

Matt Raines