WordPress: The right way to display UNIX times stored in meta values

In a recent project, I was using post metadata to store performance dates. I stored the date as a UNIX timestamp.

When it came time to use the time, I figured I could slap a date() around it and format as needed. That’s when I first came across the fact that WordPress runs in UTC time. I came across a few posts online that suggested you temporarily set the timezone of the system, and then set it back. DO NOT CHANGE THE PHP TIMEZONE WHEN USING WORDPRESS!

I then saw a few examples that would take the WordPress option for the timezone offeset and multiply it by 3600 seconds. You could then add it to a time to get the “current” time.

This usually works, however when you are dealing with events down the road, daylight savings time kicks in and screws everything up.

My solution was to useĀ get_date_from_gmt(). The Codex says that it “Simply adds the value of the ‘gmt_offset‘ option.” However, in my case, it did more than that. It also accounted for Daylight Savings Time!

Here is my code, let me know if you notice any room for improvement:

get_date_from_gmt( date( 'Y-m-d H:i:s', get_post_meta( $post->ID, '_performance_date', true ) ), get_option( 'time_format' ) )