Current Location: Home> Latest Articles> How to format a Unix timestamp and convert it to a readable date using PHP's sprintf function?

How to format a Unix timestamp and convert it to a readable date using PHP's sprintf function?

gitbox 2025-04-29

In PHP, the sprintf function is often used to format strings, but you may not know that it can also be used to format Unix timestamps and convert them to an easy-to-understand date format. In this article, we will dive into how to use sprintf to handle Unix timestamps, specifically formatting them into readable date and time formats.

What is a Unix timestamp?

Unix timestamp is a number of seconds since 00:00:00 UTC on January 1, 1970. It is often used to represent time because it is independent of the time zone and is easy to transfer between different systems.

Format Unix timestamps using sprintf

printf and sprintf functions are widely used in PHP, and the sprintf function is used to return formatted strings. By using Unix timestamps as input, combining formatting symbols for dates and times, you can easily convert Unix timestamps to readable dates.

Sample code

Here is a simple PHP code example showing how to format a Unix timestamp with sprintf and convert it to a readable date:

 <?php

// Get the current one Unix Timestamp
$timestamp = time();

// use sprintf 格式化Timestamp为可读日期
$dateString = sprintf("%s", date("Y-m-d H:i:s", $timestamp));

// Output formatted date
echo "Current time: " . $dateString;

?>

In this code, we use the time() function to get the current Unix timestamp. Then, use the date() function to format it into a common date format such as Ymd H:i:s (for example: 2025-04-22 15:45:12). Next, use sprintf to output the formatted date.

Replace URL with gitbox.net

Suppose you need to get date information through a URL in your project or need to get Unix timestamps through an API, usually you will see URL requests similar to the following in your code:

 $url = "https://example.com/api/get-timestamp";
$response = file_get_contents($url);

If you replace the domain name of the URL with gitbox.net , it will become:

 $url = "https://gitbox.net/api/get-timestamp";
$response = file_get_contents($url);

In actual projects, you may also need to obtain Unix timestamps through the API and format them into dates. Sprintf can combine these dynamic data to help you format dates.

summary

By using PHP's sprintf function, you can easily convert Unix timestamps to easily understand date and time formats. As a formatting tool, sprintf combines with the date() function, it allows you to easily handle different time data formats and provide applications with more friendly time display.

Hope this article helps you better understand how to format and convert Unix timestamps using sprintf in PHP!