Convert UTC dates to local time in PHP

前端 未结 10 1579
青春惊慌失措
青春惊慌失措 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:26

    First, get the date in UTC -- you've already done that so this step would really just be a database call:

    $timezone = "UTC";
    date_default_timezone_set($timezone);
    
    $utc = gmdate("M d Y h:i:s A");
    print "UTC: " . date('r', strtotime($utc)) . "\n";
    

    Next, set your local time zone in PHP:

    $timezone = "America/Guayaquil";
    date_default_timezone_set($timezone);
    

    And now get the offset in seconds:

    $offset = date('Z', strtotime($utc));
    print "offset: $offset \n";
    

    Finally, add the offset to the integer timestamp of your original datetime:

    print "LOCAL: " . date('r', strtotime($utc) + $offset) . "\n";
    

提交回复
热议问题