[wp-trac] [WordPress Trac] #58192: get_post_datetime() always returns local time even when using 'gmt' as $source

WordPress Trac noreply at wordpress.org
Tue Apr 25 16:36:29 UTC 2023


#58192: get_post_datetime() always returns local time even when using 'gmt' as
$source
--------------------------+-----------------------------
 Reporter:  nboole        |      Owner:  (none)
     Type:  defect (bug)  |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  Date/Time     |    Version:  6.2
 Severity:  normal        |   Keywords:
  Focuses:                |
--------------------------+-----------------------------
 This code (below) is copied directly from the github repo at
 https://github.com/WordPress/wordpress-develop/blob/6.2/src/wp-includes
 /general-template.php#L2793-L2821

 {{{#!php
 <?php
 function get_post_datetime( $post = null, $field = 'date', $source =
 'local' ) {
         $post = get_post( $post );

         if ( ! $post ) {
                 return false;
         }

         $wp_timezone = wp_timezone();

         if ( 'gmt' === $source ) {
                 $time     = ( 'modified' === $field ) ?
 $post->post_modified_gmt : $post->post_date_gmt;
                 $timezone = new DateTimeZone( 'UTC' );
         } else {
                 $time     = ( 'modified' === $field ) ?
 $post->post_modified : $post->post_date;
                 $timezone = $wp_timezone;
         }

         if ( empty( $time ) || '0000-00-00 00:00:00' === $time ) {
                 return false;
         }

         $datetime = date_create_immutable_from_format( 'Y-m-d H:i:s',
 $time, $timezone );

         if ( false === $datetime ) {
                 return false;
         }

         return $datetime->setTimezone( $wp_timezone );
 }
 }}}

 In the function above, the variable $wp_timezone is created with the
 following line: $wp_timezone = wp_timezone(); and it is never modified in
 the function, which means that $wp_timezone is always the LOCAL timezone
 for the site.

 In the if( 'gmt' === $source) part of the function, the variable $timezone
 is set based on whether or not the user asked for 'gmt' or 'local' time in
 the $source parameter.

 However, in the return statement, DateTimeImmutable::setTimezone() is
 called with the variable $wp_timezone rather than using the correctly set
 variable, $timezone.

 This means that get_post_datetime($post, 'date', 'gmt') still returns the
 WP Local time rather than GMT/UTC time as intended.

 The return statement should be re-written to: return
 $datetime->setTimezone( $timezone );

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/58192>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list