Support » Plugins » Hacks » Using PHP Timezone

  • Resolved Peter Wooster


    Both PHP and WordPress keep timezone information, and it is often different. For example my server runs in UTC and my WordPress uses EST. If you use the PHP time and date functions such as strtotime, you will end up working in your server’s timezone.

    I’ve seen a lot of code that then does
    $myTime + get_option( 'gmt_offset' ) * 3600;
    to adjust the resulting time. This mostly works, but some things will surprise you. For example if you use strtotime to convert a ‘time only’ string before midnight your time but after midnight GMT (Eg. 9pm EST) the result will be tomorrow instead of today after you adjust for the offset, since it is already tomorrow in Greenwich.

    To get this to work properly you need to tell PHP what the correct offset is so it can do its magic properly. This is done using code like

    $gofs = get_option( 'gmt_offset' ); // get WordPress offset in hours
    $tz = date_default_timezone_get(); // get current PHP timezone
    date_default_timezone_set('Etc/GMT'.(($gofs < 0)?'+':'').-$gofs); // set the PHP timezone to match WordPress
    // your code goes here
    date_default_timezone_set($tz); // set the PHP timezone back the way it was

    The ‘Etc/GMT’ timezone is PHP’s offset from Greenwich (GMT/UTC) timezone name. The offset is the negative of the one used by WordPress and it must be preceded by a + or -. When done, it’s good to set it back since some other code may be doing the same sort of thing.

    I hope this is of assistance to others who need to validate time and date values entered by users, or do other timezone related code.


  • The topic ‘Using PHP Timezone’ is closed to new replies.