Convert Unix Timestamp to time zone?

23,093

Solution 1

Use DateTime and DateTimeZone:

$dt = new DateTime('@1369490592');
$dt->setTimeZone(new DateTimeZone('America/Chicago'));
echo $dt->format('F j, Y, g:i a');

Solution 2

An easier way to do that is:

While using gmdate(), add your time zone in seconds to unix_stamp in gmdate.

Consider my time zone is GMT+5:30. So 5 hr 30 min in seconds will be 19800

So, I'll do this:

gmdate("F j, Y, g:i a", 1369490592+19800)

Share:
23,093

Related videos on Youtube

Necro.
Author by

Necro.

Updated on July 09, 2022

Comments

  • Necro.
    Necro. almost 2 years

    I have a unix timestamp that is set to +5, but I'd like to convert it to -5, EST Standard time. I would just make the time stamp be generated in that time zone, but I'm grabbing it from another source which is putting it at +5.

    Current Unmodified Timestamp Being Converted Into A Date

    <? echo gmdate("F j, Y, g:i a", 1369490592) ?>
    
  • Stefan P
    Stefan P almost 10 years
    Correct me if I'm wrong @John Surely this doesn't work? This method would use the systems (PHP Config) default timezone having not specified it when creating the instance of the DateTime object. Like here. So when converting to America/Chicago it would be altered against the system timezone assuming it's not the same as +5 like the UNIX timestamp itself which he's trying to alter by ~10 zones?
  • jmar
    jmar over 9 years
    @Stefan That is indeed wrong. Unix timestamps are always UTC. Some fun code samples: ini_set('date.timezone', 'America/Los_Angeles'); $now = time(); $utc = new DateTime("@{$now}", new DateTimeZone('America/New_York')); echo "{$utc->format('c')}\n"; // 2014-08-27T15:24:09+00:00 $utc = new DateTime("@{$now}"); echo "{$utc->format('c')}\n"; // 2014-08-27T15:24:09+00:00 ini_set('date.timezone', 'UTC'); $utc = new DateTime("@{$now}", new DateTimeZone('UTC')); echo "{$utc->format('c')}\n"; // 2014-08-27T15:24:09+00:00
  • RiotAct
    RiotAct almost 5 years
    I'm going to to throw in some advice: if your UNIX timestamp is a variable, you have to use double quotes to make it work like this: `new DateTime("@$timestamp"); if you use single quotes or no quotes, you will get an error.

Related