post: WordPress: Working with local time


WordPress: Working with local time

Working With WordPress



Linix PHP WordPress

Getting the right time when working with WordPress can be a little confusing at times. Conflicting Server, PHP and WordPress settings can lead to issues.

Most WordPress sites are hosted on Linux servers. These set the server time very accurately either as a fixed offset of UTC or relative to an NTP server, or a combination of both. Invariably PHP is set as the same timezone as the server – normally the case when the site is hosted in the same timezone/country.

This isn’t always the case though, and the timezone can be forced, either through a setting in the main php.ini file, for example: date.timezone = “Europe/London”, or within the PHP script/program with date_default_timezone_set. In more recent PHP versions if this is not set, by either of these methods, then a strict error is thrown.

As such, the time brought back by PHP via the time(), function is defined relative to the server timezone, which while often the same as the PHP setting can leading to errors in database datetime fields.

WordPress has it’s own date enforcement via the Settings > General > Timezone setting. It’s probably recommended to set this as the same as the PHP setting if at all possible.

When working exclusively within the WordPress tables – posts, taxonomy, meta data – or custom tables, I use a datetime relative to that set in the WordPress Settings > General tab. This should be set up accurately relative to your current zimezone at WordPress install / config time. WordPress then has a number of functions that can be used to retrieve an accurate & standardized datetime for use throughout the site; something plugin & theme developers should bear in mind.

Foremost in these is the current_time() function “codex link”.

   //set import date
    $dt = new DateTime();
    $dt->setTimestamp( current_time( 'timestamp' ) );
    $date = $dt->format( 'F j, Y g:i a' );

I fins it is better to use the timestamp when working with a datetime. It’s a standard and easy to convert at the endpoint. When dealing with WordPress post meta data I tend to use the timestamp as the storage type instead of the MySQL datetime format. It’s particularly useful in that format when using the post meta field in a custom WP_Query call via the meta_query argument.

comments powered by Disqus