PHP converting UTC to Local Time

2019-09-11 08:23发布

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:

3条回答
迷人小祖宗
2楼-- · 2019-09-11 08:50

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;
查看更多
甜甜的少女心
3楼-- · 2019-09-11 08:56

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.

查看更多
Animai°情兽
4楼-- · 2019-09-11 08:57

Try this:

$timestamp = '2015-10-02 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Asia/Singapore');
查看更多
登录 后发表回答