PHP date(); with timezone?

2019-01-04 09:32发布

So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date(); function? Thanks!

I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.

8条回答
别忘想泡老子
2楼-- · 2019-01-04 10:32

Try this. You can pass either unix timestamp, or datetime string

public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s') 
    {
        $datetime = is_numeric($timestamp) ?
                    DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
                    new DateTime($timestamp, new DateTimeZone($fromTimezone));

        $datetime->setTimezone(new DateTimeZone($toTimezone));

        return $datetime->format($format);
    }
查看更多
Fickle 薄情
3楼-- · 2019-01-04 10:35

You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.

查看更多
登录 后发表回答