The iso8601_timezone_to_offset() WordPress PHP function takes an ISO 8601 timezone and returns its UTC offset in seconds.
Usage
iso8601_timezone_to_offset( $timezone );
Example:
Input: iso8601_timezone_to_offset("+0200");
Output: 7200
Parameters
$timezone(string) – Required. Either ‘Z’ for 0 offset or ‘±hhmm’.
More information
See WordPress Developer Resources: iso8601_timezone_to_offset()
Examples
Convert ISO 8601 timezone to UTC offset
This code snippet converts the given ISO 8601 timezone to its UTC offset in seconds.
$timezone = "+0200"; $offset = iso8601_timezone_to_offset($timezone); echo $offset; // Output: 7200
Get UTC offset of a datetime object
This code snippet gets the UTC offset in seconds for a given datetime object.
$date = new DateTime("2023-05-05T12:00:00+02:00");
$timezone = $date->format("P");
$offset = iso8601_timezone_to_offset($timezone);
echo $offset; // Output: 7200
Calculate UTC datetime from local datetime and ISO 8601 timezone
This code snippet calculates the UTC datetime based on the local datetime and ISO 8601 timezone.
$local_datetime = "2023-05-05T12:00:00";
$timezone = "+0200";
$offset = iso8601_timezone_to_offset($timezone);
$utc_datetime = strtotime($local_datetime) - $offset;
echo gmdate("Y-m-d\TH:i:s", $utc_datetime); // Output: 2023-05-05T10:00:00
Calculate local datetime from UTC datetime and ISO 8601 timezone
This code snippet calculates the local datetime based on the UTC datetime and ISO 8601 timezone.
$utc_datetime = "2023-05-05T10:00:00";
$timezone = "+0200";
$offset = iso8601_timezone_to_offset($timezone);
$local_datetime = strtotime($utc_datetime) + $offset;
echo gmdate("Y-m-d\TH:i:s", $local_datetime); // Output: 2023-05-05T12:00:00
Compare two datetime objects with different timezones
This code snippet compares two datetime objects with different timezones and checks if they represent the same moment in time.
$date1 = new DateTime("2023-05-05T12:00:00+02:00");
$date2 = new DateTime("2023-05-05T10:00:00Z");
$timezone1 = $date1->format("P");
$offset1 = iso8601_timezone_to_offset($timezone1);
$timezone2 = $date2->format("P");
$offset2 = iso8601_timezone_to_offset($timezone2);
$utc_timestamp1 = strtotime($date1->format("Y-m-d\TH:i:s")) - $offset1;
$utc_timestamp2 = strtotime($date2->format("Y-m-d\TH:i:s")) - $offset2;
if ($utc_timestamp1 === $utc_timestamp2) {
echo "The datetimes represent the same moment in time.";
} else {
echo "The datetimes represent different moments in time.";
}