PHP Date and Time Functions
# Chapter 17: PHP Date and Time Functions
1. Introduction
Welcome to Chapter 17! When was this blog post published? How long ago did the user log in? Is their subscription expired? Managing dates and times is a fundamental part of web development. Fortunately, PHP has an incredibly robust and flexible system for handling time. In this chapter, we will learn how to get the current server time, format dates so humans can read them, and convert textual dates into computer timestamps.2. Learning Objectives
By the end of this chapter, you will be able to:- Understand Unix Timestamps.
-
Use the
time()function to get the current timestamp.
-
Format dates into readable strings using the
date()function.
-
Convert human-readable strings into timestamps using
strtotime().
- Set the correct default timezone for your application.
3. The Unix Timestamp
Computers don't inherently understand "February 10th, 2026". Instead, they count time in seconds. A Unix Timestamp is the total number of seconds that have passed since January 1, 1970 (the Unix Epoch). In PHP, thetime() function returns the current timestamp.
4. Formatting Dates with date()
A timestamp is great for computer math, but terrible for users. The date(format, timestamp) function formats a timestamp into a human-readable string based on the format characters you provide. If you omit the timestamp, it uses the current time.
Common Format Characters:
-
Y- A four-digit representation of a year (e.g., 2026)
-
m- A numeric representation of a month (01 to 12)
-
d- The day of the month (01 to 31)
-
H- 24-hour format of an hour (00 to 23)
-
i- Minutes with leading zeros (00 to 59)
-
s- Seconds with leading zeros (00 to 59)
-
l(lowercase 'L') - A full textual representation of the day of the week (e.g., Monday)
5. Setting the Timezone
By default, PHP uses the server's local timezone. If your server is in New York, but your app is for users in London, the time will be wrong. Always set your timezone explicitly at the top of your scripts.
6. Converting Strings to Time (strtotime())
One of PHP's most powerful functions is strtotime(). It parses about any English textual datetime description into a Unix timestamp.
7. Real-World Examples
Imagine calculating if a user's 30-day free trial has expired.8. Output Explanations
In the trial example, we convert the string"2026-05-01" into a pure number using strtotime. A single day has 86,400 seconds. We add 30 days worth of seconds to the start time to get the exact expiration second. We then use a simple comparison operator > against time() (the current second) to see if the trial is over!
9. Common Mistakes
-
Timezone Confusion: Forgetting to set
datedefaulttimezone_set(). This is the #1 cause of "why is my site showing the time 3 hours early?!"
-
Formatting
strtotimedirectly:strtotimereturns a large number, not a readable date. You MUST pass the result ofstrtotimeintodate()to display it.
- 2038 Problem: Standard 32-bit Unix timestamps will run out of space on January 19, 2038. Modern 64-bit PHP servers (which are standard now) solve this, but be aware of it for legacy systems!
10. Best Practices
- Store in UTC: In databases, always save timestamps or datetime strings in the UTC timezone. Convert them to the user's local timezone only when displaying them on the screen.
-
Use
Y-m-d H:i:swhen saving dates to MySQL databases, as it matches MySQL's native DATETIME format.
11. Exercises
-
1.
Echo the current year using
date(). (Useful for dynamic footer copyrights:© <?php echo date("Y"); ?>)
-
2.
Use
strtotimeto find the timestamp for "next Monday" and echo the formatted date.
12. Mini Project: Live Clock App
Task: Build a page that shows the current date and time in three different timezones dynamically.13. Coding Challenges
Challenge 1: Write a script that checks the current hour usingdate("H"). If the hour is strictly less than 12, echo "Good Morning". If less than 18, echo "Good Afternoon". Otherwise, echo "Good Evening".
14. MCQs with Answers
1. What does thetime() function return?
A) The current time formatted as "HH:MM:SS"
B) The number of seconds since January 1, 1970
C) The current year
D) A boolean value
*Answer: B*
2. Which function turns the English phrase "next Friday" into a timestamp?
A) timetext()
B) dateparse()
C) strtotime()
D) text2time()
*Answer: C*
3. Which format character represents a 4-digit year in the date() function?
A) y
B) Y
C) yy
D) YYYY
*Answer: B*
15. Interview Questions
Q: Explain the difference betweentime() and date().
*A:* time() returns the current Unix timestamp as an integer (total seconds since the Epoch). date() takes a timestamp (or uses the current time by default) and formats it into a human-readable string based on provided format characters.
Q: Why is it highly recommended to store all database times in UTC? *A:* If your server moves to a different physical location, or you have users in multiple time zones, storing local times causes massive conversion errors and data corruption (especially during Daylight Saving Time). Storing a universal standard (UTC) allows you to accurately convert to *any* user's local timezone perfectly on the frontend.
16. FAQs
Q: Does PHP update the time live on the screen like a clock? *A:* No. PHP generates the time when the server processes the page. Once the HTML is sent to the browser, it is static. To make a live ticking clock, you must use JavaScript to update the DOM every second.17. Summary
Time is on your side! You learned the fundamentals of the Unix Timestamp, how to format complex dates for user interfaces usingdate(), and the magical ability to convert English strings into math-ready timestamps using strtotime(). You also learned the crucial step of setting the correct default timezone.
18. Next Chapter Recommendation
We have used$POST, $GET, $SESSION, and $COOKIE. These are all part of a special family in PHP. In Chapter 18: PHP Superglobals, we will review this family and unlock new ones like $SERVER and $FILES!