Date and Time with PHP and WordPress
This post explains the difference between displaying the date and time with PHP vs. displaying the date and time with WordPress.
Display the Date & Time with PHP
The first line sets the timezone, which is not required but eliminates a bunch of needless warnings in PHP/error logs. The second line uses PHP’s date() function to get the date/time in the desired format. Here is one way to write it:
<?php date_default_timezone_set('America/Los_Angeles');
$date = date('F jS, Y'); ?>
With that in place, we can display the date like so:
<?php echo $date; ?>
Of course, we could turn this into a function and play with it all day long. For example, here is a nice date/time format that I like to use:
date_default_timezone_set('UTC');
$date = date('l, F jS Y @ H:i:s');
Outputs something like: “Tuesday, February 9th 2016 @ 02:22:33”
Display the Date & Time with WordPress
Update! WordPress 5.3 changes date/time functionality. Check out this post for more details and all the latest techniques.</update>
With WordPress, we also can use PHP’s date()
function, only now we can use the blog’s preferred date/time format, making it a bit more dynamic. Here is an example of the technique wrapped in a handy function:
function get_date() {
$date_format = get_option('date_format');
$time_format = get_option('time_format');
$date = date("{$date_format} {$time_format}", current_time('timestamp'));
return $date;
}
Here we are getting WP’s date_format
and time_format
options, and then using them to define the date format. We can then call the function just about anywhere:
<?php echo get_date(); ?>
Note that we can also employ the gmt_offset
option if needed:
$time_offset = get_option('gmt_offset');
These are a couple of ways to display the date and time with PHP and WordPress, hopefully they will open the doors for your own experimentation and elaboration.
Bonus!
Here is another sweet little WordPress snippet that displays the full date/time according to the admin-selected format and timezone, and as a bonus the output will be localizable so users can translate the string according to their language:
$date = date_i18n(get_option('date_format'), current_time('timestamp')) .' @ '. date_i18n(get_option('time_format'), current_time('timestamp'));
Try it out to see how it works, really a nice way of getting dynamic date and time.
Another Bonus!
Here is another trick for declaring the timezone in PHP when WordPress is available.
date_default_timezone_set(get_option('timezone_string'));
As you can see, this snippet grabs get_option('timezone_string')
from the database and uses it as the parameter of date_default_timezone_set()
.
Have fun :)