1

How do I convert the timestamp 2015-06-05 14:05:01 to another timezone using php?

I've read and tried numerous ways listed on here but I cannot get the desired result. Using date_format($date,"M d h:i A") and date_default_timezone_set('America/New_York') I get June 05 2:05 PM which is the original origin of the server timezone and correct.

What I need is to convert 2015-06-05 14:05:01 using for example date_default_timezone_set('America/Los_Angeles') and date_format($date,"M d h:i A") to get the result June 05 11:05 AM.

John Conde
  • 217,595
  • 99
  • 455
  • 496
raximus
  • 383
  • 2
  • 4
  • 13

1 Answers1

7

Use DateTime() with DateTimeZone():

// Create the DateTime() object and set the timezone to 'America/New_York'
$date = new DateTime('2015-06-05 14:05:01', new DateTimeZone('America/New_York'));

// Change the timezone to 'America/Los_Angeles'
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));

// Print out the date and time in the new timezone
echo $date->format('M d h:i A');

Demo

Easy to read which makes it easy to mantain.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Thanks again, I know I tried something similar to this many times already but I didn't have it exactly right. – raximus Jun 05 '15 at 18:40
  • 1
    When I couldn't find a dupe quickly I figured it was worth writing an answer so we have one for the future. – John Conde Jun 05 '15 at 18:41
  • I knew someone would tell me it was a dupe I've read them all, I thought it was worth posting again because I thought I might have the timestamp formatted incorrectly. – raximus Jun 05 '15 at 18:42
  • Is there a way to replace ('America/New_York') with ('-05:00')? – raximus Jun 05 '15 at 19:10
  • [This](http://stackoverflow.com/questions/7276304/php-setting-a-timezone-by-utc-offset) may be what you are looking for. – John Conde Jun 05 '15 at 19:16
  • Don't worry about it being a dup. [It's ok](http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/). – Matt Johnson-Pint Jun 05 '15 at 19:21
  • Thanks for all your answers. I really appreciate it. – raximus Jun 05 '15 at 19:21