12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Jun 22, 2022

Date and Time in WordPress – Dev Notes

Sridhar Katakam

In this article, I share the notes I put together as I was going through Date/Time component improvements in WordPress 5.3.

This will be useful for those that want to write custom code for getting the current date and time in the timezone set in WP settings, checking user-input time against the current time to determine if that was in the past or in the future etc.

What’s covered:

  • Timezone string
  • Timezone of the site as a DateTimeZone object
  • Current time as Unix timestamp
  • Current time as a Date and time object (instance of DateTimeImmutable class) using the site’s timezone
  • Current date and time in the specified format taking into account the site’s timezone setting
  • Time since the current post was published in human-readable format
  • Date and Time Comparison

Timezone string

Might return Region/Location string or ±NN:NN offset.

<?php
echo wp_timezone_string();
?>

or

<?php
echo wp_timezone()->getName();
?>

Sample output: Australia/Melbourne

Timezone of the site as a DateTimeZone object

<?php
print( '<pre>' . print_r( wp_timezone(), true ) . '</pre>' );
?>

Current time as Unix timestamp

Timestamp = Number of seconds from January 1, 1970 to the current time.

<?php
echo time();
?>

or

<?php
echo current_datetime()->format( 'U' );
?>

Sample output: 1655861239

Current time as a Date and time object (instance of DateTimeImmutable class) using the site’s timezone

<?php
print( '<pre>' . print_r( current_datetime(), true ) . '</pre>' );
?>

Current date and time in the specified format taking into account the site’s timezone setting

<?php
echo wp_date( 'Y-m-d H:i:s' );
?>

Sample output: 2022-06-22 11:42:33

Reference for date formats: https://wordpress.org/support/article/formatting-date-and-time/

Developer Resources page.

Time since the current post was published in human-readable format

<?php
echo human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) );
?>

Sample output for a post published on 24 Nov 2021 as on 22 Jun 2022: 7 months

Date and Time Comparison

<?php
// Create a new DateTime object using the user-supplied date string in the timezone set in WP settings.
$value = '2023-03-21 16:29:00';

$date_input_object = new DateTimeImmutable( $value, wp_timezone() );

// format it into a Unix timestamp
$date_input_timestamp = $date_input_object->format( 'U' );

// compare the user supplied time with current time
if ( time() > $date_input_timestamp ) {
	echo 'The specified time is in the past.';
} elseif ( time() < $date_input_timestamp ) {
	echo 'The specified time is in the future.';
} elseif ( time() === $date_input_timestamp ) {
	echo 'It is currently the specified time.';
}
?>
tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-down