Using WordPress ‘parse_w3cdtf()’ PHP function

The parse_w3cdtf() WordPress PHP function converts a W3C DTF formatted date string into a Unix timestamp.

Usage

$timestamp = parse_w3cdtf($date_string);

Example:

$date_string = "2023-05-04T15:30:00Z";
$timestamp = parse_w3cdtf($date_string);
// Output: 1680785400

Parameters

  • $date_string (string) – The W3C DTF formatted date string to be converted.

More information

See WordPress Developer Resources: parse_w3cdtf()

Examples

Convert W3C DTF string to Unix timestamp

Converts a W3C DTF formatted date string into a Unix timestamp and displays the timestamp.

$date_string = "2023-05-04T15:30:00Z";
$timestamp = parse_w3cdtf($date_string);
echo $timestamp; // Output: 1680785400

Convert W3C DTF string to formatted date

Converts a W3C DTF formatted date string into a Unix timestamp, then formats the date using the desired format.

$date_string = "2023-05-04T15:30:00Z";
$timestamp = parse_w3cdtf($date_string);
$formatted_date = date('Y-m-d H:i:s', $timestamp);
echo $formatted_date; // Output: 2023-05-04 15:30:00

Calculate the difference between two W3C DTF dates

Converts two W3C DTF formatted date strings into Unix timestamps and calculates the difference between them in days.

$date_string1 = "2023-05-04T15:30:00Z";
$date_string2 = "2023-05-07T15:30:00Z";
$timestamp1 = parse_w3cdtf($date_string1);
$timestamp2 = parse_w3cdtf($date_string2);
$diff_in_days = abs($timestamp2 - $timestamp1) / 86400;
echo $diff_in_days; // Output: 3

Check if a W3C DTF date is within a specified range

Determines whether a W3C DTF formatted date string falls within a specified date range.

$date_string = "2023-05-05T15:30:00Z";
$start_date = "2023-05-01T00:00:00Z";
$end_date = "2023-05-10T23:59:59Z";
$timestamp = parse_w3cdtf($date_string);
$start_timestamp = parse_w3cdtf($start_date);
$end_timestamp = parse_w3cdtf($end_date);

if ($timestamp >= $start_timestamp && $timestamp <= $end_timestamp) {
    echo "Date is within range.";
} else {
    echo "Date is not within range.";
}

Get day of the week from W3C DTF date

Converts a W3C DTF formatted date string into a Unix timestamp, then gets the day of the week.

$date_string = "2023-05-04T15:30:00Z";
$timestamp = parse_w3cdtf($date_string);
$day_of_week = date('l', $timestamp);
echo $day_of_week; // Output: Thursday