In PHP, handling timezones and timestamps is a common task. The timezone_name_get and mktime functions are two very useful tools that help us calculate Unix timestamps for specific timezones. This article explains how to use these two functions to achieve that, along with a simple example code.
The timezone_name_get function returns the timezone name of a given DateTimeZone object. This timezone name is usually in the Region/City format, such as America/New_York or Asia/Shanghai.
Usage example:
$timezone = new DateTimeZone('Asia/Shanghai');
echo timezone_name_get($timezone);
Output:
Asia/Shanghai
The mktime function is used to calculate the Unix timestamp of a specific time. It accepts multiple parameters specifying the year, month, day, hour, minute, and second. This function is commonly used to convert local time into a Unix timestamp.
Usage example:
$timestamp = mktime(14, 30, 0, 6, 12, 2025);
echo $timestamp;
The output is the Unix timestamp for June 12, 2025, 14:30:00.
When calculating Unix timestamps for specific timezones, the timezone_name_get and mktime functions need to be used together. The approach is as follows:
Get timezone information via timezone_name_get.
Create a DateTimeZone object and set it to the target timezone.
Create a DateTime object and set it to the time in that timezone.
Use the mktime function to convert the time into a Unix timestamp.
Below is a complete example combining timezone_name_get and mktime to calculate the Unix timestamp for a specific date and time in a particular timezone (e.g., Asia/Shanghai):
<?php
// Target timezone
$timezone = new DateTimeZone('Asia/Shanghai');
<p>// Get timezone name<br>
$timezone_name = timezone_name_get($timezone);<br>
echo "Target timezone: " . $timezone_name . "\n";</p>
<p>// Create DateTime object and set to specific time<br>
$date = new DateTime('2025-06-12 14:30:00', $timezone);</p>
<p>// Use mktime function to convert to Unix timestamp<br>
$timestamp = mktime($date->format('H'), $date->format('i'), $date->format('s'),<br>
$date->format('m'), $date->format('d'), $date->format('Y'));</p>
<p>echo "Corresponding Unix timestamp: " . $timestamp . "\n";<br>
?><br>
Create a DateTimeZone object: First, we specify the target timezone (such as Asia/Shanghai).
Get the timezone name: Use timezone_name_get to retrieve and output the timezone name.
Create a DateTime object: The DateTime constructor accepts a datetime string and a timezone object. We set the target time (June 12, 2025, 14:30:00) to this object.
Calculate Unix timestamp using mktime: Extract hour, minute, second, month, day, and year from the DateTime object and pass them to mktime to get the Unix timestamp.
By combining the timezone_name_get and mktime functions, we can easily calculate Unix timestamps for specific timezones. Mastering these techniques allows you to handle timezone-related time calculations more precisely, which is especially useful in cross-timezone applications.