Backend Development 4 min read

Getting the Current UNIX Timestamp in PHP and Common Use Cases

This article explains how to obtain the current UNIX timestamp in PHP using the built‑in time() function, demonstrates code examples for displaying the timestamp, calculating yesterday’s date, and sorting an array of timestamps, and discusses common scenarios where timestamps are useful.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Getting the Current UNIX Timestamp in PHP and Common Use Cases

A UNIX timestamp is the total number of seconds that have elapsed since Coordinated Universal Time (UTC) 00:00:00 on January 1, 1970. In PHP, you can use the built‑in function time() to obtain the current UNIX timestamp.

Code example:

<?php
$timestamp = time();
echo "当前的UNIX时间戳是:" . $timestamp;
?>

The above code first calls the time function to get the current UNIX timestamp, then uses echo to output it. Running the code will print the current UNIX timestamp as an integer representing the seconds since 1970‑01‑01 00:00:00.

UNIX timestamps can be used for various time‑related operations, such as calculating time intervals or sorting times. Below are some common use cases.

1. Calculating time intervals

You can compute a time interval by subtracting one timestamp from another. The following example calculates yesterday’s date.

<?php
$yesterday = time() - (24 * 60 * 60);
echo "昨天的日期是:" . date("Y-m-d", $yesterday);
?>

In this code, the current timestamp is reduced by the number of seconds in 24 hours to obtain yesterday’s timestamp, which is then formatted into a date string with the date function and printed.

2. Sorting times

UNIX timestamps can be used to sort times. For instance, an array containing multiple timestamps can be sorted with the built‑in sort function, resulting in chronological order from earliest to latest.

<?php
$timestamps = array(1609459200, 1610136600, 1610741400);
sort($timestamps);
print_r($timestamps);
?>

The code defines an array of three timestamps, sorts it with sort , and prints the sorted array, which will be ordered from the earliest to the latest time.

Conclusion

Using PHP’s time() function provides an easy way to retrieve the current UNIX timestamp, an integer that can be leveraged for many time‑related tasks. This article presented common scenarios and corresponding code examples.

backend developmentPHPUnix 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

login 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.