Understanding PHP time() Function: Usage, Examples, and Applications

This article explains PHP's time() function, describing how it returns the current Unix timestamp, demonstrates basic usage with code examples, shows how to compare dates and format the timestamp, and provides practical snippets for common time‑related tasks in backend development.

php Courses
php Courses
php Courses
Understanding PHP time() Function: Usage, Examples, and Applications

PHP is a widely used server‑side scripting language, and its time() function is one of the most common utilities for handling timestamps.

1. Purpose of time()

The time() function returns the current Unix timestamp, i.e., the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970.

2. How to use time()

The function takes no arguments; calling it directly yields an integer representing the current timestamp.

Basic usage example:

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

The script outputs the current Unix timestamp.

3. Practical code examples

a) Output the current timestamp

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

b) Determine whether a specific date has passed

<?php
    $targetDate = strtotime("2023-02-15");
    $currentTime = time();

    if ($currentTime > $targetDate) {
        echo "指定日期已过去";
    } else {
        echo "指定日期尚未到来";
    }
?>

This example uses strtotime() to convert a date string to a timestamp and compares it with the current timestamp.

c) Get the current date and time

<?php
    date_default_timezone_set('Asia/Shanghai');

    $currentTime = time();
    $currentDate = date("Y-m-d", $currentTime);
    $currentTime = date("H:i:s", $currentTime);

    echo "当前日期:" . $currentDate . "<br>";
    echo "当前时间:" . $currentTime;
?>

Here date_default_timezone_set() sets the timezone, and date() formats the timestamp into readable date and time strings.

Conclusion

The time() function provides a simple way to obtain the current Unix timestamp, which can then be transformed with date() or compared with other timestamps for various time‑related operations in PHP.

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.

BackendPHPdate handlingtimeunix timestamp
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.