Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 374
zeckdude Avatar asked Nov 29 '09 07:11

zeckdude


People also ask

What is timestamp format in PHP?

What is a TimeStamp? A timestamp in PHP is a numeric value in seconds between the current time and value as at 1st January, 1970 00:00:00 Greenwich Mean Time (GMT). The value returned by the time function depends on the default time zone. The default time zone is set in the php.

How can I get only hours from time in PHP?

By hours I'm assuming you mean if the time is 8PM or 20:00 hours like it is in your time string then... $date = "2011-07-26 20:05:00"; $date = strtotime($date); echo date('H', $date);

How can I write current time in PHP?

echo "The time is " . date("h:i:sa"); ?> Note that the PHP date() function will return the current date/time of the server!


1 Answers

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.

like image 157
cletus Avatar answered Oct 21 '22 11:10

cletus