Convert UTC dates to local time in PHP

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

    Here is a straight way to convert the UTC time of the questioner to local time. This is for a stored time in a database etc., i.e. any time. You just have to find the time difference between UTC time and the local time you are interested in and then ajust the stored UTC time adding to it the difference.

    $df = "G:i:s";  // Use a simple time format to find the difference
    $ts1 = strtotime(date($df));   // Timestamp of current local time
    $ts2 = strtotime(gmdate($df)); // Timestamp of current UTC time
    $ts3 = $ts1-$ts2;              // Their difference
    

    You can then add this difference to the stored UTC time. (In my place, Athens, the difference is exactly 5:00:00)

    Example:

    $time = time() // Or any other timestamp
    $time += $ts3  // Add the difference
    $dateInLocal = date("Y-m-d H:i:s", $time);
    

提交回复
热议问题