Home > Backend Development > PHP Tutorial > How to Format Unix Timestamps as Date Strings in PHP?

How to Format Unix Timestamps as Date Strings in PHP?

Mary-Kate Olsen
Release: 2024-11-11 22:24:03
Original
399 people have browsed it

How to Format Unix Timestamps as Date Strings in PHP?

Formatting Unix Timestamps as Date Strings in PHP

Converting Unix timestamps to formatted date strings is a common task in PHP-based applications. By formatting these numerical representations, you can display timestamps in a human-readable format, such as "2008-07-17T09:24:17Z".

For example, you want to convert a timestamp like 1333699439 to the string "2008-07-17T09:24:17Z". To achieve this, you can use the gmdate() function, which formats a timestamp according to the specified format string. Here's how you can do it:

<?php
$timestamp = 1333699439;
$formattedDate = gmdate("Y-m-d\TH:i:s\Z", $timestamp);
echo $formattedDate;
?>
Copy after login

In this code, the gmdate() function is used with the following format string:

  • "Y": Year, represented as a 4-digit string
  • "m": Month, represented as a 2-digit string (01 to 12)
  • "d": Day of the month, represented as a 2-digit string (01 to 31)
  • "T": Separator between date and time
  • "H": Hours (24-hour format), represented as a 2-digit string (00 to 23)
  • "i": Minutes, represented as a 2-digit string (00 to 59)
  • "s": Seconds, represented as a 2-digit string (00 to 59)
  • "Z": Zulu time (UTC)

By composing these format specifiers, you can create a custom date string format that matches your desired output. The gmdate() function will then apply this format to the provided timestamp, resulting in a formatted date string in UTC time.

The above is the detailed content of How to Format Unix Timestamps as Date Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template