Master PHP’s time() Function: Get Unix Timestamps & Build Date Logic
Learn how PHP’s built-in time() function returns the current Unix timestamp, how to use it without parameters, and see practical code examples for displaying timestamps, comparing dates with strtotime(), and formatting dates with date() and timezone settings.
PHP is a widely used server-side language with a rich function library. The time() function is one of the common time functions in PHP. This article explains its purpose, usage, and provides concrete code examples.
Purpose of time()
The time() function is a built-in PHP function that returns the current Unix timestamp (the number of seconds since 00:00:00 UTC on 1 January 1970).
How to Use time()
The function takes no arguments; simply call it. It returns an integer representing the current Unix timestamp.
Below is a basic usage example:
<?php
$timestamp = time();
echo "Current timestamp: " . $timestamp;
?>The above code outputs the current Unix timestamp.
Code Examples for time()
Output Current Timestamp
<?php
$timestamp = time();
echo "Current timestamp: " . $timestamp;
?>Determine whether a specific date has passed:
<?php
$targetDate = strtotime("2023-02-15");
$currentTime = time();
if ($currentTime > $targetDate) {
echo "The specified date has passed";
} else {
echo "The specified date has not arrived yet";
}
?>Getting Current Date and Time
<?php
date_default_timezone_set('Asia/Shanghai');
$currentTime = time();
$currentDate = date("Y-m-d", $currentTime);
$currentTimeFormatted = date("H:i:s", $currentTime);
echo "Current date: " . $currentDate . "<br>";
echo "Current time: " . $currentTimeFormatted;
?>In this example we set the timezone to Shanghai with date_default_timezone_set(), then use date() to format the timestamp into readable date and time strings.
The time() function is a convenient way to obtain the current Unix timestamp, which can be converted and manipulated for various time-related operations using functions like strtotime() and date().
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.
