PHP converting UTC to Local Time

我与影子孤独终老i 提交于 2019-12-25 06:42:19

问题


In my postgresql, the I have the following column named "created" that has the type timestamp with timezone

So I inserted the record according to the format as such which I believe is UTC.

2015-10-02 09:09:35+08

I am using php Carbon library so i did the following:

$date = Carbon\Carbon::parse('2015-10-02 09:09:35+08');
echo  $date->->toDatetimeString(); 
//gives result as 2015-10-02 09:09:35

How can I use the library to echo the correct timezone which includes the adding of the +8 in the above datetime format? The timzezone that I am using is "Asia/Singapore".

The time should be printed to local timing which is 2015-10-02: 17:09:35:


回答1:


You can do this using native php without using Carbon:

$time = '2015-10-02 16:34:00+08';
$date = DateTime::createFromFormat('Y-m-d H:i:s+O', $time);
print $date->format('Y-m-d H:i:s') . PHP_EOL;
$date->setTimeZone(new DateTimeZone('Asia/Singapore'));
print $date->format('Y-m-d H:i:s') . PHP_EOL;
$date->setTimeZone(new DateTimeZone('Etc/UTC'));
print $date->format('Y-m-d H:i:s') . PHP_EOL;



回答2:


Try this using standard PHP:

$raw = '2015-10-02 09:09:35+08';
$date = substr($raw,0,19);
$tzOffset = (strlen($raw) > 19) ? substr($raw,-3) : 0;
$timestamp = strtotime($date) + (60 * 60 * $tzOffset);
$localTime = date('Y-m-d H:i:s',$timestamp);
echo 'local time:['.$localTime.']';

The result is:

local time:[2015-10-02 17:09:35]

This will also work without a time zone offset or a negative one.




回答3:


Try this:

$timestamp = '2015-10-02 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Asia/Singapore');


来源:https://stackoverflow.com/questions/32904530/php-converting-utc-to-local-time

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