Timezone conversion in php

后端 未结 9 1701
我寻月下人不归
我寻月下人不归 2020-11-22 04:19

Can anyone suggest an easy method to convert date and time to different timezones in php?

9条回答
  •  青春惊慌失措
    2020-11-22 04:38

    This worked for me and it's pretty clean too!

    function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
    {
        try {
            $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
            $dateTime->setTimezone(new DateTimeZone($userTimeZone));
            return $dateTime->format($format);
        } catch (Exception $e) {
            return '';
        }
    }
    
    function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
    {
        try {
            $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
            $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
            return $dateTime->format($format);
        } catch (Exception $e) {
            return '';
        }
    }
    
    //example usage
    $serverDate = $userDate = '2014-09-04 22:37:22';
    echo convert_to_user_date($serverDate);
    echo convert_to_server_date($userDate);
    

提交回复
热议问题