Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTC Date/Time String to Timezone

Tags:

timezone

php

utc

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.

like image 614
amax Avatar asked Apr 21 '11 15:04

amax


People also ask

How do you convert UTC to timezone?

(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.

What is UTC time string?

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.

How do I convert datetime to timezone?

DateTime currentTime = TimeZoneInfo. ConvertTime(DateTime. Now, TimeZoneInfo. FindSystemTimeZoneById("Central Standard Time"));

How do you convert date to UTC format?

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.


2 Answers

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'); 
like image 191
Kevin Peno Avatar answered Oct 11 '22 07:10

Kevin Peno


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

like image 30
Miguel Avatar answered Oct 11 '22 08:10

Miguel