Function and usage of get_gmt_from_date() in wordpress

Question

Answers ( 1 )

    0
    2024-01-06T22:42:06+00:00

    The get_gmt_from_date() function in WordPress is used to convert a date from the local timezone of the WordPress site to UTC (Coordinated Universal Time). This function is particularly useful when you need to work with dates in a consistent timezone across various locations, especially for sites that cater to a global audience.

    Function Syntax:

    get_gmt_from_date( string $date_string, string $format = 'Y-m-d H:i:s' ): string
    

    Description:

    • Purpose: It takes a date in the local timezone of the site and converts it to the UTC timezone.
    • Return Format: The function returns the date in the 'Y-m-d H:i:s' format by default, but this can be changed using the $format parameter.

    Parameters:

    1. $date_string (string, required): This is the date you want to convert. It should be in the format that represents the local timezone of your WordPress site.

    2. $format (string, optional): This parameter allows you to specify the format in which you want the UTC date to be returned. It defaults to 'Y-m-d H:i:s', but you can provide any format string supported by PHP's date function.

    Return:

    • Type: string
    • Description: It returns the formatted version of the date in UTC according to the format specified by the $format parameter or the default format if no format is specified.

    Sample Usage:

    Let's say your WordPress site is set to the EST timezone, and you have a date string '2024-01-07 15:00:00' which you want to convert to UTC.

    $date_string = '2024-01-07 15:00:00'; // Date in site's timezone (e.g., EST)
    $utc_date = get_gmt_from_date($date_string); // Convert to UTC
    
    // Output the UTC date in default format
    echo $utc_date; // Outputs something like '2024-01-07 20:00:00' in UTC
    

    If you want the date in a different format, for example, 'd/m/Y H:i', you can specify that in the $format parameter:

    $utc_date_custom_format = get_gmt_from_date($date_string, 'd/m/Y H:i');
    echo $utc_date_custom_format; // Outputs in '07/01/2024 20:00' format
    

    This function is very handy for date-time conversions in WordPress development, especially when dealing with events or data that are time-sensitive and need to be standardized to UTC.

Leave an answer