Convert UTC dates to local time in PHP

前端 未结 10 1583
青春惊慌失措
青春惊慌失措 2020-11-28 07:16

I\'m storing the UTC dates into the DB using:

$utc = gmdate(\"M d Y h:i:s A\");

and then I want to convert the saved UTC date to the client

10条回答
  •  粉色の甜心
    2020-11-28 07:33

    Answer

    Convert the UTC datetime to America/Denver

    // create a $dt object with the UTC timezone
    $dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
    
    // change the timezone of the object without changing it's time
    $dt->setTimezone(new DateTimeZone('America/Denver'));
    
    // format the datetime
    $dt->format('Y-m-d H:i:s T');
    

    Notes

    time() returns the unix timestamp, which is a number, it has no timezone.

    date('Y-m-d H:i:s T') returns the date in the current locale timezone.

    gmdate('Y-m-d H:i:s T') returns the date in UTC

    date_default_timezone_set() changes the current locale timezone

    to change a time in a timezone

    // create a $dt object with the America/Denver timezone
    $dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('America/Denver'));
    
    // change the timezone of the object without changing it's time
    $dt->setTimezone(new DateTimeZone('UTC'));
    
    // format the datetime
    $dt->format('Y-m-d H:i:s T');
    

    here you can see all the available timezones

    https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

    here are all the formatting options

    http://php.net/manual/en/function.date.php

    Update PHP timezone DB (in linux)

    sudo pecl install timezonedb
    

提交回复
热议问题