The iso8601_to_datetime() WordPress PHP function converts a given ISO 8601 date format (Ymd\TH:i:sO) into a MySQL DateTime format (Y-m-d H:i:s) used by post_date[_gmt].
Usage
iso8601_to_datetime( string $date_string, string $timezone = 'user' );
Custom example:
Input:
iso8601_to_datetime('2023-05-05T12:34:56+00:00', 'gmt');
Output:
'2023-05-05 12:34:56'
Parameters
$date_string (string)
– Required. Date and time in ISO 8601 format. For more information, see ISO 8601.$timezone (string)
– Optional. If set to ‘gmt’, the function returns the result in UTC. Default is ‘user’. Default value: ‘user’.
More information
See WordPress Developer Resources: iso8601_to_datetime()
Examples
Convert ISO 8601 date to MySQL DateTime format (user timezone)
In this example, we convert an ISO 8601 date to the MySQL DateTime format for the user’s timezone.
$date_string = '2023-05-05T12:34:56+00:00'; $converted_date = iso8601_to_datetime($date_string); echo $converted_date; // Output: '2023-05-05 12:34:56' (or adjusted to user's timezone)
Convert ISO 8601 date to MySQL DateTime format (UTC timezone)
In this example, we convert an ISO 8601 date to the MySQL DateTime format for the UTC timezone.
$date_string = '2023-05-05T12:34:56+00:00'; $converted_date = iso8601_to_datetime($date_string, 'gmt'); echo $converted_date; // Output: '2023-05-05 12:34:56'
Convert ISO 8601 date to MySQL DateTime format and save as post_date
In this example, we convert an ISO 8601 date to the MySQL DateTime format and save it as the post_date for a new post.
$date_string = '2023-05-05T12:34:56+00:00'; $converted_date = iso8601_to_datetime($date_string); $post_data = array( 'post_date' => $converted_date, 'post_title' => 'Example Post', 'post_content' => 'This is an example post.', 'post_status' => 'publish' ); $post_id = wp_insert_post($post_data);
Convert ISO 8601 date to MySQL DateTime format and update post_date
In this example, we convert an ISO 8601 date to the MySQL DateTime format and update the post_date for an existing post.
$post_id = 1; // Replace with an existing post ID $date_string = '2023-05-05T12:34:56+00:00'; $converted_date = iso8601_to_datetime($date_string); $post_data = array( 'ID' => $post_id, 'post_date' => $converted_date ); wp_update_post($post_data);
Convert ISO 8601 date to MySQL DateTime format and display in a post’s metadata
In this example, we convert an ISO