Search code examples
phpyiiphp-carbon

PHP converting UTC to Local Time


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:


Solution

  • 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;