Master PHP Time Functions: Get, Format, Calculate, and Set Timezones
This tutorial explains how to use PHP's time(), date(), strtotime(), and date_default_timezone_set() functions to retrieve the current timestamp, format dates, perform date arithmetic, and configure timezones, providing practical code examples for each operation.
In PHP development, handling dates and times is a common task, and PHP offers powerful functions to simplify these operations.
Getting the current time
Use time() to obtain the current Unix timestamp. Example:
$current_time = time();
echo $current_time;Convert the timestamp to a readable format with date():
$current_time = time();
$date = date('Y-m-d H:i:s', $current_time);
echo $date;Formatting dates and times
The date() function accepts format characters such as Y (year), m (month), d (day), H (hour), i (minute), and s (second). Example:
$current_time = time();
$date = date('Y-m-d H:i:s', $current_time);
echo $date;Time calculations
Use strtotime() to parse human‑readable strings into timestamps. Adding one day:
$future_time = strtotime('+1 day');
$date = date('Y-m-d', $future_time);
echo $date;Calculating the difference between two dates:
$start_date = strtotime('2021-11-01');
$end_date = strtotime('2021-11-05');
$diff_days = ($end_date - $start_date) / (60 * 60 * 24);
echo $diff_days;Setting the timezone
Set the default timezone with date_default_timezone_set(). Example for Shanghai:
date_default_timezone_set('Asia/Shanghai');
$current_time = time();
$date = date('Y-m-d H:i:s', $current_time);
echo $date;Conclusion
This guide covered the most common PHP time functions—including retrieving the current time, formatting dates, performing calculations, and configuring timezones—helping developers handle time‑related tasks efficiently.
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.
