Backend Development 5 min read

Using PHP Timestamp Functions: time(), strtotime(), date(), and Related Utilities

This article explains how to use PHP's timestamp functions—including time(), strtotime(), date(), and mktime()—to obtain current timestamps, convert strings to timestamps, format dates, handle time zones, and perform relative time calculations with practical code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP Timestamp Functions: time(), strtotime(), date(), and Related Utilities

PHP timestamp functions are powerful tools for time conversion and calculation. This article summarizes their usage and important considerations.

time() Function Usage

The time() function returns the current Unix timestamp, i.e., the number of seconds since January 1, 1970 00:00:00 GMT.

<code>$timestamp = time();
echo $timestamp;</code>

To format a timestamp into a readable date, use the date() function:

<code>$timestamp = time();
$date = date("Y-m-d H:i:s", $timestamp);
echo $date;</code>

This outputs the current date and time, for example 2020-01-01 12:00:00 .

strtotime() Function Usage

The strtotime() function converts a date‑time string into a Unix timestamp.

<code>$time = strtotime("2020-01-01");
echo $time;</code>

You can also provide a second argument as the base timestamp for relative calculations:

<code>$time = strtotime("next Monday", time());
echo $time;</code>

This outputs the timestamp for the upcoming Monday.

Other useful time functions include mktime() for creating a timestamp from individual date components:

<code>$timestamp = mktime(12, 0, 0, 1, 1, 2020);
echo $timestamp;</code>

And using strtotime() with relative expressions:

<code>$timestamp = strtotime("+1 day", $timestamp);
echo $timestamp;</code>

When working with timestamps, setting the correct time zone is essential. Use date_default_timezone_set() to define the desired zone:

<code>date_default_timezone_set('Asia/Shanghai');</code>

Be aware of special cases such as leap years and daylight‑saving time, which may require additional handling or external libraries.

Overall, PHP timestamp functions are versatile for converting and calculating dates, but developers should pay attention to time‑zone settings and edge cases.

PHP Learning Recommendations

Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Master Course

Workerman+TP6 Real‑time Chat System – Limited Time Offer

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