How to Retrieve UTC Time Stamps in PHP
Getting the current time stamp in PHP is straightforward using the date() function. However, by default, date() returns timestamps based on the server's time zone. To obtain timestamps in Coordinated Universal Time (UTC), we need to utilize a different approach.
Solution: Using gmdate()
To retrieve timestamps in UTC, we can use the gmdate() function in PHP. gmdate() works similarly to date() but always returns timestamps in UTC regardless of the server's time zone. The syntax is identical to date(), allowing you to format the timestamp as needed.
Example:
<code class="php">$utcTimestamp = gmdate("Y-m-d H:i:s"); echo "UTC Timestamp: $utcTimestamp";</code>
This will display the current timestamp in UTC format. Additionally, we can append the time zone offset to the timestamp using the gmstrftime() function.
Example:
<code class="php">$timeZoneOffset = gmstrftime("%z"); $utcTimestampWithOffset = gmdate("Y-m-d H:i:s") . " GMT/UTC" . $timeZoneOffset; echo "UTC Timestamp with Offset: $utcTimestampWithOffset";</code>
This will output the UTC timestamp with the appropriate time zone offset, such as "2023-03-08 14:30:00 GMT/UTC 0800" if the server's time zone is 8 hours ahead of UTC.
The above is the detailed content of How to Retrieve UTC Time Stamps in PHP?. For more information, please follow other related articles on the PHP Chinese website!