PHP function showing wrong time in WordPress

My local WordPress installation on XAMPP seems to have a wrong time setting. When I do

date( 'Y-m-d H:i:s' );

I get 2017-02-21 10:46:43 as result. However my PCs time really is 2017-02-21 11:46:43, so my WordPress is one hour behind.

Now I already did, what was recommended here and changed date.timezone in the php.ini to my timezone and restarted the apache afterwards, since I thought the problem might be cause by XAMPP. But still I get the wrong time displayed.

I also went to settings -> general in WordPress and changed the timezone there to the correct one. The local time shown there is correct:

"Local time is 2017-02-21 11:46:43"

But when I use the function, it's still wrong. Do you have any idea, what else could cause this problem?

Topic xampp php timezones date-time Wordpress

Category Web


It seems Wordpress overrides the php Timezone to save all dates as UTC. But they also do a poor job in converting it back to local time.

I have run into the same problem and did some testing to find a solution.

1st of all this is not a PHP timezone Problem, to confirm this I put a test.php into my theme folder and opened it directly (/wp-content/themes/theme/test.php)

if I use the date() function in this file the time is correct.

but if I put this lines into e.g. my themes home.php

print date('Y-m-d H:i:s');
print current_time('Y-m-d H:i:s');

I get the wrong time when I visit the Homepage.

date() returns UTC and current_time() return the time of the right timezone but it does not include DST so I'm still 1 hour off.

what i ended up doing is this:

$row = $wpdb->get_row( "SELECT CURRENT_TIMESTAMP() AS timestamp", ARRAY_A);
$timestamp = $row['timestamp'];

if your database has the right config for your timezone you can ask your database for the Timestamp.

But this also has some downsides, it will only work if your Database has right timezone and it always does a Query to the database so you should not use it to excessive.


use wordpress functions to get time according to WordPress settings and time zone such as the_time and the_date

 the_date('F j, Y');
 the_time('g:i a');

date() is a PHP function depending on your server settings. You can go around that by using the WordPress function:

current_time( 'Y-m-d H:i:s' );

This function takes the settings in wp-admin into account.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.