Home >Backend Development >PHP Tutorial >How to Convert a UNIX Timestamp to ISO 8601 Date String in PHP?

How to Convert a UNIX Timestamp to ISO 8601 Date String in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 12:03:02557browse

How to Convert a UNIX Timestamp to ISO 8601 Date String in PHP?

Converting UNIX Timestamps to ISO 8601 Date Strings in PHP

As we delve into the intricacies of web development, it often becomes necessary to manipulate timestamps and convert them into human-readable formats. UNIX timestamps, represented as the number of seconds since the epoch (usually January 1, 1970, 00:00:00 UTC), provide a convenient way to track time. However, for display or storage purposes, we often need to convert these timestamps into more structured date strings.

问题:

In PHP, how can we convert a UNIX timestamp, such as 1333699439, into a formatted date string in the ISO 8601 format (e.g., 2008-07-17T09:24:17Z)?

答案:

PHP provides the gmdate() function, which allows us to format timestamps. The following example demonstrates how to achieve the desired conversion:

$timestamp = 1333699439;
$dateString = gmdate("Y-m-d\TH:i:s\Z", $timestamp);

The gmdate() function uses the following format specifiers:

  • Y: Year with leading zeros
  • m: Month with leading zeros
  • d: Day of the month with leading zeros
  • H: Hour (24-hour format) with leading zeros
  • i: Minute with leading zeros
  • s: Second with leading zeros
  • Z: Time zone offset in "Zulu" format (e.g., " 00:00" for UTC)

By combining these specifiers, we can create date strings in various formats, including the ISO 8601 format shown in the example. The resulting date string, "2008-07-17T09:24:17Z," represents July 17, 2008, at 09:24:17 UTC.

The above is the detailed content of How to Convert a UNIX Timestamp to ISO 8601 Date String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn