Code
The current (2020) correct code to display a full date and time in localized form is via the new WordPress core function wp_date()
:
echo wp_date( get_option( 'date_format' ), get_post_timestamp() )
. wp_date( get_option( 'time_format' ), get_post_timestamp() );
This relatively short code snippet:
- obeys the requested formatting options for date and time from WordPress Settings
- does the appropriate translations
- applies the correct timezone from Settings
- is considered best practice in 2021 and forward.
Rationale
With the release of wp_date()
in WordPress 5.3 (2019), WordPress has moved a long way towards fixing the confusing and broken way that time worked within WordPress, specifically, the problem where WordPress timestamps were not the same as Unix timestamps (aka the value of time()) but had the timezone offset added. The confusion arose because in the Unix world, the output of time() (aka "Unix timestamp") was historically always in GMT form, and was compounded by the use of the term "unix timestamp" to describe these "WordPress timestamps". The new function wp_date()
does the localization you'd normally need and works correctly with supplied GMT timestamp values.
Note that using PHP's date_default_timezone_set()
to set a site timezone (other than locally) will still break WordPress, but now there are nice alternatives that work as one would expect. It's worth noting that the use of date_default_timezone_set()
is now detected in Site Health as 'critical' since it will break time handling within WordPress and some plugins; if you do use it in old code you should remove it as soon as you can and replace your use of date()
with wp_date()
.
Documentation
A more complete introduction to the new date and time functions, written by the team that developed the new code, is here:
https://make.wordpress.org/core/2019/09/23/date-time-improvements-wp-5-3/
Note that some of the new functions return PHP DateTimeImmutable
objects which makes life considerably easier. Additionally all of the functions listed in the linked introduction are now core and thus have core PHP manual pages in the usual places.
Also, they do include notes on what to use, and what not to use (though at the moment, they lack code examples).