How do I convert a date/time string (e.g. 2011-01-01 15:00:00) that is UTC to any given timezone php supports, such as America/New_York, or Europe/San_Marino.
(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.
DateTime currentTime = TimeZoneInfo. ConvertTime(DateTime. Now, TimeZoneInfo. FindSystemTimeZoneById("Central Standard Time"));
The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.
PHP's DateTime
object is pretty flexible.
$UTC = new DateTimeZone("UTC"); $newTZ = new DateTimeZone("America/New_York"); $date = new DateTime( "2011-01-01 15:00:00", $UTC ); $date->setTimezone( $newTZ ); echo $date->format('Y-m-d H:i:s');
PHP's DateTime
object is pretty flexible.
Since the user asked for more than one timezone option, then you can make it generic.
Generic Function
function convertDateFromTimezone($date,$timezone,$timezone_to,$format){ $date = new DateTime($date,new DateTimeZone($timezone)); $date->setTimezone( new DateTimeZone($timezone_to) ); return $date->format($format); }
Usage:
echo convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');
Output:
2011-04-21 09:14:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With