Created
May 19, 2016 17:16
-
-
Save nitishn/da2792b3d62a0b40cf62ce0f2f947b9b to your computer and use it in GitHub Desktop.
Working with dates in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Working with dates is annoying. Time is annoying, especially with timezones involved. | |
// In WP, you have to worry about the timezone set by WordPress AND the timezone set in php.ini. | |
// A safe bet when working with date logic in WP, is to assume that the timezone set by the WP backend is correct. | |
// More than likely, an event is local and thus should use WP timezone. | |
// HOWEVER, when working with php's DateTime class, you need to manually set the timezone or you'll have | |
// inconsistant dates! Below is a snippet which helps set the timezone, does calculations, and then sets it back. | |
// Set to WP timezone | |
$phpTimezone = date_default_timezone_get(); | |
if( get_option('timezone_string') ) date_default_timezone_set( get_option('timezone_string') ); | |
// Correct way to get today's date. | |
$today = new \DateTime(current_time( 'Y-m-d' )); | |
// Flip it back to php timezone | |
date_default_timezone_set($phpTimezone); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment