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条回答
We Are One
2楼-- · 2019-01-04 10:17

The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:

$myTimestamp = 123456789;

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp($myTimestamp);

return $dt->format('F j, Y @ G:i');
查看更多
孤傲高冷的网名
3楼-- · 2019-01-04 10:23

Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::format.

An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.

You'll want to store in the database as UTC and convert on the application level.

查看更多
男人必须洒脱
4楼-- · 2019-01-04 10:25

If I understood correct,You need to set time zone first like:

date_default_timezone_set('UTC');

And than you can use date function:

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
查看更多
Anthone
5楼-- · 2019-01-04 10:26

I have created this very straightforward function, and it works like a charm:

function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */            
        $date = new DateTime(date("d F Y H:i:s",$timestamp));
        $date->setTimezone(new DateTimeZone($timezone));
        $rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
        return $rt;
    }
查看更多
狗以群分
6楼-- · 2019-01-04 10:27

It should like this:

date_default_timezone_set('America/New_York');
查看更多
别忘想泡老子
7楼-- · 2019-01-04 10:31

For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.

I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.

Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:

$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');

DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).

查看更多
登录 后发表回答