[wp-trac] [WordPress Trac] #40653: Use PHP `DateTime` class API in `current_time()`

WordPress Trac noreply at wordpress.org
Wed May 3 20:41:37 UTC 2017


#40653: Use PHP `DateTime` class API in `current_time()`
-------------------------+-----------------------------
 Reporter:  jdgrimes     |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  Date/Time    |    Version:  1.0
 Severity:  normal       |   Keywords:
  Focuses:               |
-------------------------+-----------------------------
 The `current_time()` function has been in WordPress for a long time. It
 was introduced before PHP offered the robust `DateTime` class and
 surrounding API that was introduced in 5.2. This was back in the days of
 hoary old things like PHP 4, and these were still formative years. Without
 ceremony, in [549], `current_time()` was born as a helper function to
 replace this code from b2:

 {{{#!php
 <?php
 $time_difference = get_settings("time_difference");
 $now = date("Y-m-d H:i:s",(time() + ($time_difference * 3600)));
 }}}

 In the intervening years the function has remained little changed, as far
 as the underlying design goes. But the method of calculating local dates
 by using offsets from UTC is no longer necessary. It is now a hack, solved
 by PHP a short eternity ago, and is prone to confuse new devs and provide
 them a bad pattern to follow.

 This is made worse by the fact that the function is not very transparent.
 It appears not to use the site's timezone in its calculations at all.
 Instead, it uses GMT offsets, which in fact only approximate the site's
 timezone, without regard for daylight savings and other quirks. Actually
 though, the `wp_timezone_override_offset()` function is hooked to the
 `'pre_option_gmt_offset'` filter behind the scenes to correctly calculate
 the offset for a particular moment in time from the site's timezone
 string, if set.

 The real heart of the problem, though, is that `current_time()` always
 calculates dates in UTC time. So passing a custom format will have
 unexpected results if timezone-related information is included (as
 [https://core.trac.wordpress.org/ticket/38940#comment:8 pointed out by
 @Rarst]).

 I believe that we can make `current_time()` less confusing and less buggy
 by utilizing the powerful tools now built into PHP, specifically, the
 `DateTime` object and its support for timezone-relative calculations. See
 the attached patch for an example.

 In summary, this will:

 - Fix a bug when passing custom timezone-referencing format strings.
 - Make the function's behavior more transparent.
 - Provide a better pattern for learning devs to follow.

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


More information about the wp-trac mailing list