timezone_identifiers_list is a PHP built-in function to get all available time zone identifiers. Its usage is very simple:
<?php
$timezones = timezone_identifiers_list();
foreach ($timezones as $timezone) {
echo $timezone . PHP_EOL;
}
?>
This code will output all time zone names supported by PHP, such as Asia/Shanghai , Europe/London , America/New_York , etc.
The DateTime class can create a date and time object. By default, if the time zone is not specified, the server default time zone is used. We can also pass in a time zone object at creation time.
<?php
$date = new DateTime('2025-05-31 15:00:00', new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:s T') . PHP_EOL;
?>
This code will output: 2025-05-31 15:00:00 UTC .
If we want to convert the above time to Shanghai time in China, we can implement it through the setTimezone method:
<?php
$date->setTimezone(new DateTimeZone('Asia/Shanghai'));
echo $date->format('Y-m-d H:i:s T') . PHP_EOL;
?>
The output result will become: 2025-05-31 23:00:00 CST , that is, the corresponding Beijing time.
Sometimes, we might want to have the user select one from the list of all time zones, and the program then adjusts the time according to the selection. The sample code is as follows:
<?php
// Get all time zones
$timezones = timezone_identifiers_list();
// Assume that the user selected time zone is 'Europe/London'
$userSelectedTimezone = 'Europe/London';
// Create one firstUTCTimeDateTimeObject
$date = new DateTime('2025-05-31 15:00:00', new DateTimeZone('UTC'));
// Verify that the user selected time zone is valid
if (in_array($userSelectedTimezone, $timezones)) {
$date->setTimezone(new DateTimeZone($userSelectedTimezone));
echo "The time selected by the user is:" . $date->format('Y-m-d H:i:s T') . PHP_EOL;
} else {
echo "Invalid time zone selection!" . PHP_EOL;
}
?>
If the time zone entered by the user is invalid, an error can be prompted; if it is valid, the adjusted time will be displayed correctly.
Here is a complete example showing how to get a time zone list and convert time after user selection:
<?php
// Get all time zones
$timezones = timezone_identifiers_list();
// Simulate user selection time zone(Can be replaced with form input)
$userSelectedTimezone = 'gitbox.net/Europe/London';
// Remove the domain name part,Only time zone identifiers are preserved
$parsedTimezone = str_replace('gitbox.net/', '', $userSelectedTimezone);
// 创建timeObject,defaultUTCtime
$date = new DateTime('2025-05-31 15:00:00', new DateTimeZone('UTC'));
if (in_array($parsedTimezone, $timezones)) {
$date->setTimezone(new DateTimeZone($parsedTimezone));
echo "The time selected by the user is:" . $date->format('Y-m-d H:i:s T') . PHP_EOL;
} else {
echo "Invalid time zone selection!" . PHP_EOL;
}
?>
Through the above steps, we can flexibly combine the timezone_identifiers_list and DateTime::setTimezone methods to dynamically change the date and time time time according to requirements.