How to Get and Use UNIX Timestamps in PHP
This guide explains what a UNIX timestamp is, shows how to retrieve the current timestamp with PHP's time() function, and provides practical examples for calculating time intervals and sorting timestamps using simple PHP code.
UNIX timestamps count the total seconds elapsed since 00:00:00 UTC on 1 January 1970. In PHP you can obtain the current timestamp instantly with the built‑in time() function.
Getting the Current Timestamp
<?php
$timestamp = time();
echo "Current UNIX timestamp: " . $timestamp;
?>The script above stores the current timestamp in $timestamp and prints it. The output is a single integer representing the number of seconds since the epoch.
Common Use Cases
1. Calculating Time Intervals
You can compute differences between timestamps to find durations, such as the date of yesterday.
<?php
$yesterday = time() - (24 * 60 * 60); // subtract one day in seconds
echo "Yesterday's date: " . date("Y-m-d", $yesterday);
?>This code subtracts 86,400 seconds (24 hours) from the current timestamp, then formats the result as a readable date.
2. Sorting Timestamps
When you have an array of timestamps, PHP’s sort() function can order them chronologically.
<?php
$timestamps = array(1609459200, 1610136600, 1610741400);
sort($timestamps);
print_r($timestamps);
?>The array is reordered from the earliest to the latest timestamp, and print_r displays the sorted list.
Conclusion
Using PHP’s time() function provides a straightforward way to work with UNIX timestamps, which are essential for many time‑related operations such as interval calculations and chronological sorting. The examples above demonstrate typical scenarios and the minimal code required to implement them.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
