Function and usage of iso8601_to_datetime() in wordpress


Answers ( 1 )


    The iso8601_to_datetime() function in WordPress is a utility for converting dates from ISO 8601 format to MySQL DateTime format. This function is particularly useful when dealing with dates and times in different formats, especially when working with post dates in WordPress.

    Function Signature

    iso8601_to_datetime( string $date_string, string $timezone = 'user' ): string|false


    1. $date_string (string, required): The date and time you want to convert, provided in ISO 8601 format. ISO 8601 is an international standard for date and time representations and is often used in data interchange. It looks like this: Ymd\TH:i:sO (e.g., 20240109T15:30:00+0000).

    2. $timezone (string, optional): Specifies the timezone for the conversion. It can be set to:

      • 'gmt': to get the result in Coordinated Universal Time (UTC).
      • 'user': to get the result in the timezone of the current user. This is the default value.

    Return Value

    • string|false: The function returns the date and time in MySQL DateTime format (Y-m-d H:i:s). For example, 2024-01-09 15:30:00. If the conversion fails for any reason, it returns false.

    Sample Usage

    Here's an example of how to use iso8601_to_datetime() in a WordPress context:

    $date_iso8601 = "20240109T15:30:00+0000"; // ISO 8601 formatted date
    // Convert to MySQL DateTime format in the user's timezone
    $date_mysql_user = iso8601_to_datetime($date_iso8601, 'user');
    // Convert to MySQL DateTime format in GMT/UTC
    $date_mysql_gmt = iso8601_to_datetime($date_iso8601, 'gmt');
    // Check and display results
    if ($date_mysql_user !== false && $date_mysql_gmt !== false) {
        echo "User Timezone: " . $date_mysql_user . "\n";
        echo "GMT Timezone: " . $date_mysql_gmt;
    } else {
        echo "Conversion failed.";

    In this example, an ISO 8601 date is converted to MySQL DateTime format for both the user's timezone and GMT/UTC. The function can handle different timezone offsets within the ISO 8601 format and accurately converts them to the specified timezone in the MySQL DateTime format.

Leave an answer