Convert Unix Timestamp to time zone?

南楼画角 提交于 2019-12-18 11:53:36

问题


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) ?>

回答1:


Use DateTime and DateTimeZone:

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



回答2:


As because edit queue for John Conde's answer is full I'll add more detailed answer.

From DateTime::__construct(string $time, DateTimeZone $timezone)

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800)…

This is the main reason why you should always specify timezone, even default, when creating DateTime objects from unix timestamp. See explained code inspired by John Conde's answer:

$dt = new DateTime('@1369490592');

// use your default timezone to work correctly with unix timestamps
// and in line with other parts of your application
date_default_timezone_set ('America/Chicago'); // somewhere on bootstrapping time
…
$dt->setTimeZone(new DateTimeZone(date_default_timezone_get()));

// set timezone to convert time to the other timezone
$dt->setTimeZone(new DateTimeZone('America/Chicago'));

echo $dt->format('F j, Y, g:i a');



回答3:


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)




回答4:


Here is a function to convert unix/gmt/utc timestamp to required timezone, that might interest you.

function unix_to_local($timestamp, $timezone){
    // Create datetime object with desired timezone
    $local_timezone = new DateTimeZone($timezone);
    $date_time = new DateTime('now', $local_timezone);
    $offset = $date_time->format('P'); // + 05:00

    // Convert offset to number of hours
    $offset = explode(':', $offset);
    if($offset[1] == 00){ $offset2 = ''; }
    if($offset[1] == 30){ $offset2 = .5; }
    if($offset[1] == 45){ $offset2 = .75; }
    $hours = $offset[0].$offset2 + 0;

    // Convert hours to seconds
    $seconds = $hours * 3600;

    // Add/Subtract number of seconds from given unix/gmt/utc timestamp
    $result = floor( $timestamp + $seconds );

    return $result;
}


来源:https://stackoverflow.com/questions/16750447/convert-unix-timestamp-to-time-zone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!