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.

php Courses
php Courses
php Courses
How to Get and Use UNIX Timestamps in PHP

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendunix timestampdate calculationtime function
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.