Why is my time() off by one hour in php?

2019-02-08 20:36发布

问题:

I am adding the current date and time to my database using the following code:

$current_date_time = time();
echo date('n/j/y g:ia',$current_date_time);

It shows up as 11/29/09 12:38am when it should be 11/29/09 11:38am

The time is ahead by one hour. I am in the Pacific time zone and my hosting provider is in Utah, the Mountain Time Zone. Could this be the reason why it is ahead by one hour?

How do I solve this problem? Do I need to remove an hour from the time? If so, how do I do that? Or is there some sort of other way to account for time zone differences so it shows up in Pacific Time Zone time?

回答1:

You solve it by setting the timezone explicitly in your PHP scripts. You can do this with date_default_timezone_set():

date_default_timezone_set('America/Los_Angeles');

Here is the list of PHP supported timezones.

You may also want to try a test script calling date_default_timezone_get() to see what it's actually set to to verify that this is in fact the problem.