Skip to main content
PHP for Beginners
CHAPTER 17 Beginner

PHP Date and Time Functions

Updated: May 12, 2026
20 min read

# 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, the time() function returns the current timestamp.
php
12345
<?php
$current_time = time();
echo "Seconds since Jan 1, 1970: " . $current_time;
// Outputs something like: 1770000000
?>

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)

php
123456789
<?php
// Typical Database Format
echo date("Y-m-d H:i:s"); // Outputs: 2026-05-12 14:30:00

echo "<br>";

// Human Readable Format
echo date("l, F jS, Y"); // Outputs: Tuesday, May 12th, 2026
?>

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.
php
1234
<?php
date_default_timezone_set("Europe/London");
echo "London Time: " . date("h:i:s A");
?>

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.
php
12345678
<?php
$timestamp1 = strtotime("10:30pm April 15 2026");
$timestamp2 = strtotime("tomorrow");
$timestamp3 = strtotime("+1 week 2 days 4 hours");

// Formatting the calculated timestamps
echo "Next week is: " . date("Y-m-d", $timestamp3);
?>

7. Real-World Examples

Imagine calculating if a user's 30-day free trial has expired.
php
12345678910111213141516
<?php
$trial_start_date = "2026-05-01"; // Stored in database

// Convert start date to timestamp
$start_timestamp = strtotime($trial_start_date);

// Add 30 days of seconds (30 * 24 * 60 * 60)
$expiration_timestamp = $start_timestamp + (30 * 86400);

if (time() > $expiration_timestamp) {
    echo "Your free trial has expired! Please upgrade.";
} else {
    $days_left = floor(($expiration_timestamp - time()) / 86400);
    echo "You have $days_left days left in your trial.";
}
?>

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 strtotime directly: strtotime returns a large number, not a readable date. You MUST pass the result of strtotime into date() 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:s when saving dates to MySQL databases, as it matches MySQL's native DATETIME format.

11. Exercises

  1. 1. Echo the current year using date(). (Useful for dynamic footer copyrights: &copy; <?php echo date("Y"); ?>)
  1. 2. Use strtotime to 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.
php
123456789101112131415161718192021222324252627282930313233343536
<?php
// Function to fetch and format time for a specific timezone
function getTimeInZone($timezone) {
    date_default_timezone_set($timezone);
    return date("l, F j, Y - h:i:s A");
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>World Clock</title>
    <style>
        .clock-card { border: 1px solid #ccc; padding: 15px; margin-bottom: 10px; width: 300px; font-family: monospace; }
        h3 { margin-top: 0; }
    </style>
</head>
<body>
    <h2>Global Operations Clock</h2>
    
    <div class="clock-card">
        <h3>🇺🇸 New York (EST)</h3>
        <p><?php echo getTimeInZone("America/New_York"); ?></p>
    </div>

    <div class="clock-card">
        <h3>🇬🇧 London (GMT)</h3>
        <p><?php echo getTimeInZone("Europe/London"); ?></p>
    </div>

    <div class="clock-card">
        <h3>🇯🇵 Tokyo (JST)</h3>
        <p><?php echo getTimeInZone("Asia/Tokyo"); ?></p>
    </div>
</body>
</html>

13. Coding Challenges

Challenge 1: Write a script that checks the current hour using date("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 the time() 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 between time() 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 using date(), 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!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·