November 1, 2017 / Web/
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.
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.
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.