Convert UTC to local time
Published August 4th, 2012 under General
I was having a dreadful time converting from the UTC time stamp stored in the WordPress database to the local time set in the admin panel. I ended up writing the following handy little function to convert the times easily. There may be a better way to do this, so if any of you know of an improved solution please let me know in the comments 🙂
/* * Converts UTC time to local time as set in WordPress * Processes data in the format "Y-m-d H:i:s" (same format as used in WordPress core) * * @author Ryan Hellyer <ryanhellyer@gmail.com> */ function convert_time( $time ) { $timestamp = strtotime( $time ); // Converting time to Unix timestamp $offset = get_option( 'gmt_offset' ) * 60 * 60; // Time offset in seconds $local_timestamp = $timestamp + $offset; $local_time = date_i18n( 'Y-m-d H:i:s', $local_timestamp ); return $local_time; } $time = '2012-08-03 12:33:07'; echo convert_time( $time );
John Blackbourn says:
There's actually a little-used function in core for this called <code>get_date_from_gmt()</code>, but it's not too intuitive.
It accepts a date string in the format "Y-m-d H:i:s" (rather than a Unix timestamp) and returns the date converted to local time and formatted according to the <code>$format</code> parameter.
It works but it does mean your code gets a little messy:
<code>echo get_date_from_gmt( date( 'Y-m-d H:i:s', $my_timestamp ), get_option( 'date_format' ) )</code>
John
July 20, 2013 at 2:22 pm # //
Ryan says:
Awesome. Thanks for letting me know 🙂
July 20, 2013 at 5:33 pm # //
Mike says:
Thanks, works great!
November 16, 2015 at 8:36 pm # //
Ryan says:
Awesome 🙂
November 27, 2015 at 12:47 am # //