Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting between timezones in PHP

I am converting this time and date:

Thu, 31 Mar 2011 02:05:59 GMT 

To the following time and date format:

Monday March 28 2011 4:48:02 PM 

I am using the following PHP code to accomplish this, but I want to convert all time zones to PST/PDT. I looked at the PHP manual and saw this date_default_timezone_set() but I am not sure how to implement that into the code I have below.

$date = $messages[0]->CreationTime; echo date('l F j Y g:i:s A I', strtotime($date)) 
like image 494
FAFAFOHI Avatar asked Mar 31 '11 16:03

FAFAFOHI


People also ask

How do I convert one time zone to another in php?

php $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru')); echo $date->format('Y-m-d H:i:sP') . "\n"; $date->setTimezone(new DateTimeZone('Pacific/Chatham')); echo $date->format('Y-m-d H:i:sP') .

How do you change from one time zone to another?

Changing Timezones of ZonedDateTime To convert a ZonedDateTime instance from one timezone to another, follow the two steps: Create ZonedDateTime in 1st timezone. You may already have it in your application. Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.


2 Answers

I would not use date_default_timezone_set for general TZ conversions. (To clarify... if this is for display purposes, script wide, then using the default timezone is a reasonable thing to do.)

Instead, I would use something like:

$tz = new DateTimeZone('America/Los_Angeles');  $date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT'); $date->setTimezone($tz); echo $date->format('l F j Y g:i:s A I')."\n"; 
like image 177
Matthew Avatar answered Oct 10 '22 08:10

Matthew


$date = $messages[0]->CreationTime; date_default_timezone_set('America/Los_Angeles'); echo date('l F j Y g:i:s A I', strtotime($date)); 

See this list for available timezones that get passed into the function

like image 23
Mike B Avatar answered Oct 10 '22 06:10

Mike B