WordPress has always had a difficult relationship with timezones. Until recently, you couldn’t specify named timezone regions (only UTC offsets), and even today you can’t expect to use some of PHP’s built-in datetime functions without coming up against timezone issues. To overcome some issues, I’ve created a version of PHP’s Date() and StrToTime() functions that correctly handles local times in WordPress.

The first function – wp_strtotime() – accepts one input parameter, and utilises the DateTime and DateTimeZone classes, along with the configured local timezone in WordPress, to return the date as Unix timestamp.

Here’s the function:


The second function – wp_date_localised() – accepts two input parameters (the format and timestamp strings), and returns the timestamp converted to the specified format in your local timezone.

Here’s the function:


You can use this code in your own themes or functions (it’s probably best to preface the function names with your own namespace). Simply input a timestamp in any of the usual PHP valid formats, and you get a Unix Timestamp back. To convert the other way, input the format & Unix Timestamp to get a local, formatted string back.

This code attempts to use the WordPress options timezone_string‘ and ‘gmt_offset’ when parsing the provided timestamp.

DateTime code is difficult. While researching this issue I found a lot of mis-information and frankly dangerous information. This code attempts to fix those misconceptions about DateTime in WordPress. If you find any unaccounted edge cases, or have discovered a better way to deal with this issue, please feel free to make a comment below or on Github.

I’ve used this code myself in some bespoke client plugins, as well as my new MetaRadio WordPress Plugin. It’s proven a handy way to accept localised datetime input and convert it to Unix time where it can be handled appropriately.

Get the Broadcast Technology Newsletter

Sign up for the email newsletter about media and technology. Sent irregularly. No spam.

I'm Anthony Eden, and I'm a IT Professional, Broadcast Technician, Software Developer, and Solutions Engineer. I've been working in broadcast media since 2008, and developing software and websites for just as long. Right now, I provide freelance services through Media Realm - in particular, to the media and not-for-profit industries.

Follow Anthony on Twitter: @anthony_eden