Understanding PHP time() Function: Purpose, Usage, and Code Examples
This article explains PHP's built‑in time() function, describing its role in returning the current Unix timestamp, demonstrating usage without parameters, and providing multiple code examples—including basic timestamp output, date comparison with strtotime(), and formatted date/time retrieval after setting the timezone.
PHP is a widely used server‑side programming language with a powerful function library. The time() function is one of the commonly used time functions in PHP. This article details its purpose, usage, and provides concrete code examples.
Purpose of the time() Function
The time() function is a built‑in PHP function that returns the current Unix timestamp (the number of seconds elapsed since 1970‑01‑01 00:00:00 UTC).
How to Use the time() Function
The time() function takes no arguments; simply call it. It returns an integer representing the current Unix timestamp.
Below is a basic usage example:
<code><?php
$timestamp = time();
echo "当前时间戳:" . $timestamp;
?>
</code>The above code outputs the current Unix timestamp.
Code Examples of the time() Function
Output Current Timestamp
<code><?php
$timestamp = time();
echo "当前时间戳:" . $timestamp;
?>
// Determine if a specific date has passed
<?php
$targetDate = strtotime("2023-02-15");
$currentTime = time();
if($currentTime > $targetDate) {
echo "指定日期已过去";
} else {
echo "指定日期尚未到来";
}
?>
</code>In the above code we use strtotime() to convert the specified date into a Unix timestamp and compare it with the current timestamp to determine whether the date has already passed.
Get Current Time
<code><?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;
?>
</code>In this example we set the timezone to Shanghai using date_default_timezone_set() , then use date() to format the current timestamp into separate date and time strings and output them.
The time() function is a commonly used PHP time function that conveniently obtains the current Unix timestamp. By converting timestamps, various time‑related operations and judgments can be performed. Additionally, the date() function can convert timestamps into different date and time formats. We hope this article helps you better understand and use the time() function.
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.