Using WordPress ‘mysql_to_rfc3339()’ PHP function

The mysql_to_rfc3339() WordPress PHP function parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601 (Y-m-d\TH:i:s).

Usage

mysql_to_rfc3339( $date_string );

Example:

Input:

mysql_to_rfc3339( '2023-05-04 12:30:00' );

Output:

'2023-05-04T12:30:00'

Parameters

  • $date_string (string) (Required): Date string to parse and format.

More information

See WordPress Developer Resources: mysql_to_rfc3339()

Examples

Convert a MySQL datetime to ISO8601 format

This example converts a MySQL datetime to the ISO8601 format.

$date_string = '2023-05-04 12:30:00';
$formatted_date = mysql_to_rfc3339( $date_string );
echo $formatted_date; // Output: '2023-05-04T12:30:00'

Format a date from a custom post type

This example retrieves a custom post type’s date and formats it using mysql_to_rfc3339().

$post_id = 123;
$post_date = get_post( $post_id )->post_date;
$formatted_date = mysql_to_rfc3339( $post_date );
echo $formatted_date;

Format the current date and time

This example formats the current date and time using mysql_to_rfc3339().

$current_date = current_time( 'mysql' );
$formatted_date = mysql_to_rfc3339( $current_date );
echo $formatted_date;

Format a date from a meta value

This example retrieves a date stored as a meta value and formats it using mysql_to_rfc3339().

$post_id = 123;
$meta_key = 'event_date';
$event_date = get_post_meta( $post_id, $meta_key, true );
$formatted_date = mysql_to_rfc3339( $event_date );
echo $formatted_date;

Format a date from a comment

This example retrieves a comment’s date and formats it using mysql_to_rfc3339().

$comment_id = 456;
$comment_date = get_comment( $comment_id )->comment_date;
$formatted_date = mysql_to_rfc3339( $comment_date );
echo $formatted_date;