Using WordPress ‘current_datetime()’ PHP function

The current_datetime() WordPress PHP function retrieves the current time as an object using the site’s timezone.

Usage

To use the current_datetime() function, simply call it like this:

$current_time = current_datetime();
echo $current_time->format('Y-m-d H:i:s');

This would output the current date and time in the format ‘YYYY-MM-DD HH:MM:SS’.

Parameters

  • The current_datetime() function does not require any parameters.

More information

See WordPress Developer Resources: current_datetime()

This function was implemented in WordPress 5.3.0.

Examples

Display Current Date and Time

In this example, we’re displaying the current date and time in the format ‘YYYY-MM-DD HH:MM:SS’.

// Get current datetime
$current_time = current_datetime();

// Display current datetime
echo $current_time->format('Y-m-d H:i:s');

Display Current Date

If you only want to display the current date, use this code:

// Get current datetime
$current_time = current_datetime();

// Display current date
echo $current_time->format('Y-m-d');

Display Current Time

To display the current time, you can use this code:

// Get current datetime
$current_time = current_datetime();

// Display current time
echo $current_time->format('H:i:s');

Compare Current Date with a Specific Date

To compare the current date with a specific date, you can use the following code:

// Get current datetime
$current_time = current_datetime();

// Specific date
$specific_date = new DateTime('2023-12-31');

// Compare dates
if ($current_time > $specific_date) {
    echo "The current date is later than the specific date.";
} else {
    echo "The specific date is later than the current date.";
}

Add Days to Current Date

If you want to add days to the current date and display the result, you can use this code:

// Get current datetime
$current_time = current_datetime();

// Add 5 days to the current date
$current_time->modify('+5 days');

// Display the new date
echo $current_time->format('Y-m-d');