How can I easily convert dates from UTC via PHP?

前端 未结 8 2358
梦谈多话
梦谈多话 2020-12-01 17:07

I am storing dates in a MySQL database in datetime fields in UTC. I\'m using PHP, and I\'ve called date_timezone_set(\'UTC\') so that all calls to date() (without timestamp)

8条回答
  •  半阙折子戏
    2020-12-01 17:53

    This worked for me and it's pretty clean

    function convert_to_user_date($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
    {
        $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
        $dateTime->setTimezone(new DateTimeZone($userTimeZone));
        return $dateTime->format($format);
    }
    
    function convert_to_server_date($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
    {
        $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
        $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
        return $dateTime->format($format);
    }
    

提交回复
热议问题