PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
53: Working with Dates: DateTime and DateInterval
If you've been using the basic date() and strtotime() functions, you've probably realized they're fine for simple timestamps, but they quickly become a nightmare when you're doing actual "date math." That's where the DateTime class and DateInterval come in. They treat dates as objects rather than strings, which makes your life much easier.
To show you how this works in a real scenario, let's build a small piece of logic for a subscription service. We need to take a user's sign-up date, calculate their next billing date (one month later), and figure out exactly how many days are left until that happens.
Pinpointing the current moment
First, I'll start by creating a DateTime object. I'm not going to hardcode a date because I want to see it work in real-time. By calling the constructor without arguments, PHP assumes "now."
<?php
$signupDate = new DateTime();
echo "You signed up on: " . $signupDate->format('Y-m-d H:i:s') . "\n";
?>
I prefer using format() over the old date() function because the object carries its own state. It's cleaner and more portable.
Calculating the next bill date
Now, I need to move that date forward by one month. This is where DateInterval comes in. This class represents a fixed amount of time (like "one month" or "three days") rather than a specific point on a calendar.
<?php
// I'll try to create an interval for one month
$interval = new DateInterval('1 month');
$signupDate->add($interval);
echo "Next billing date: " . $signupDate->format('Y-m-d');
?>
Wait—I just hit a fatal error. I did this in my first few years of PHP too. I instinctively passed "1 month" into the DateInterval constructor. But DateInterval doesn't take human-readable English; it requires an ISO 8601 duration string. The "P" stands for Period, and the "M" stands for Months.
Let me fix that:
<?php
// Correcting the interval string to ISO 8601 format
$interval = new DateInterval('P1M');
$signupDate->add($interval);
echo "Next billing date: " . $signupDate->format('Y-m-d');
?>
Measuring the gap between dates
Adding time is great, but often you need to go the other way: finding the difference between two dates. For this, we use the diff() method. This method actually returns a DateInterval object, which is pretty convenient.
Let's say we want to tell the user exactly how many days they have left. I'll create a second object for "today" so I can compare it against the billing date we just calculated.
<?php
$today = new DateTime();
$billingDate = new DateTime();
$billingDate->add(new DateInterval('P1M'));
$difference = $today->diff($billingDate);
echo "Your next bill is in " . $difference->days . " days.";
?>
One thing to keep in mind: $difference->days gives you the total number of days. If you wanted the breakdown (like "1 month and 2 days"), you'd access properties like $difference->m or $difference->d. For a countdown, days is almost always what you actually want.
- DateTime: A specific point in time.
- DateInterval: A duration of time.
- diff(): A way to find the distance between two points.
📋 Practical Task
Build a Trial Expiration Countdown
You are building a "Trial Period" feature for a software app. A user signs up for a 14-day free trial.
Write a PHP script that does the following:
- Creates a
DateTimeobject representing the user's sign-up date (you can use "now"). - Uses
DateIntervalto calculate the expiration date exactly 14 days after sign-up. - Creates a second
DateTimeobject representing "today" (simulating a check that happens a few days into the trial). To make this realistic, manually set this "today" date to be 5 days after the sign-up date. - Calculates the difference between "today" and the expiration date.
- Prints a message: "Your trial expires in X days." (where X is the calculated difference).
There are no comments for now.