📖 PHP Working with Dates
📅 Core Concepts
Dates and times are essential to many web applications — from displaying today's schedule to calculating deadlines. In PHP, dates and times can be represented and manipulated in two core ways:
- Unix Timestamps: Simple integer values representing seconds since January 1, 1970 (UTC)
- DateTime Objects: Full-featured objects that provide methods for formatting, comparison, and manipulation
| Feature | Unix Timestamp | DateTime Object |
|---|---|---|
| Type | Integer (e.g., 1721824052) |
Object (DateTime) |
| Format | Seconds since Unix epoch | Human-readable date & time |
| Use cases | Fast storage, math, comparisons | Flexible formatting, date math, OOP features |
| Functions used | time(), mktime(), strtotime(), getdate() |
date_create(), date_format(), modify() |
| Conversion | Use date() to format |
Use date_timestamp_get() to get a timestamp |
| Mutability | Not applicable (it's just a number) | Mutable (via object methods) |
| Readability | Not human-friendly | Highly readable and adaptable |
This article introduces both approaches and shows how to work with them using built-in PHP functions and methods.
⏱ Understanding Timestamps
PHP time uses a Unix timestamp. From Wikipedia: "Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds; the Unix epoch is 00:00:00 UTC on 1 January 1970." It is important to understand this concept as the timestamp is central to the PHP time and date functions.
You can explore and convert timestamps using the Epoch Converter.
🧭 Universal Time vs Local Time
Think of UTC (Coordinated Universal Time) as a single moment — like a snapshot of the whole Earth taken from space. At that exact moment, the Earth is in a specific position relative to the Sun. Everyone on Earth experiences that same moment, but the local clock time is different depending on where you are.
If you're in London (UTC+0), your watch shows 00:00 when the Unix epoch begins. If you're in Dallas (UTC-6), your watch shows 18:00 the previous day because London is ahead of us in solar time — it reaches midnight there six hours before we do. IE: our time is behind England by 6 hours. The moment is the same — it's just your position on Earth that shifts the reading on your clock.
This is why timestamps (like those from time() or strtotime()) are considered timezone-independent. They store a point in time. When you format them for display (like with date() or DateTime::format()), that's when the local timezone matters.
YouTube has a good explainer video on Timezones and UTC.
🌎 Working with Timezones
PHP's date and time functions operate in the server's default timezone, which may not match your users' local time. To ensure consistent behavior, you can set the default timezone for your script using date_default_timezone_set().
Use date_default_timezone_set() to control the output timezone for your script.
date_default_timezone_set('America/Chicago');
echo date_default_timezone_get();
For more options, see the full timezone list.
🕒 Core Functions
time()
Returns the current time (timestamp) measured in the number of seconds since the Unix Epoch (January 1, 1970 00:00:00 GMT).
The time() function is often used when generating timestamps, calculating time intervals, or working with formatted dates via other functions like date().
echo time();
// returns something like 1721234567
date()
The date() function formats a local date/time string based on a given Unix timestamp. If no timestamp is provided, it defaults to the current server time.
string date(string $format, int $timestamp = time())
The format string consists of one or more characters that represent various parts of a date or time. Here are the most commonly used codes:
| Code | Description | Example Output |
|---|---|---|
d |
Day of the month (two digits) | 07 |
j |
Day of the month (no leading zero) | 7 |
S |
Ordinal suffix for day (st, nd, rd, th) | th |
w |
Day of the week (0 = Sunday) | 1 |
z |
Day of the year (0 to 365) | 212 |
l |
Full day name | Monday |
D |
Three-letter day name | Mon |
F |
Full month name | July |
m |
Month (two digits) | 07 |
n |
Month (no leading zero) | 7 |
t |
Days in the month | 31 |
L |
Leap year (1 = yes, 0 = no) | 0 |
Y |
Four-digit year | 2025 |
y |
Two-digit year | 25 |
H |
24-hour format | 14 |
h |
12-hour format (two digits) | 02 |
g |
12-hour format (no leading zero) | 2 |
A |
Uppercase AM/PM | PM |
i |
Minutes | 45 |
s |
Seconds | 09 |
e |
Timezone identifier | America/Chicago |
Examples
// uses current server date as default
echo date("l");
// Output: Monday
echo date("l dS \\of F Y h:i:s A");
// Output: Monday 24th of July 2025 02:45:09 PM
// output using a specific timestamp
echo date("F j, Y, g:i A", strtotime("2025-12-25 10:30:00"));
// Output: December 25, 2025, 10:30 AM
strtotime()
The strtotime() function takes a human-readable string — such as "next Saturday" or "April 15, 2014" — and converts it into a Unix timestamp. It's one of the most flexible tools in PHP for parsing and calculating relative or specific dates.
// Convert a specific time string to a timestamp
$day = strtotime("10:30 pm April 15, 2014");
echo date("m/d/Y h:i:sA", $day);
// Output: "04/15/2014 10:30:00PM"
// or convert a date to a timestamp then format it
$timestamp = strtotime("2025-12-25 10:30:00");
echo date("F j, Y, g:i A", $timestamp);
// Output: December 25, 2025, 10:30 AM
// Examples of strtotime() with relative phrases
$day = strtotime("tomorrow");
$day = strtotime("next Saturday");
$day = strtotime("+3 Months");
$day = strtotime("December 25");
mktime()
The mktime() function lets you build a timestamp from individual date/time components. This is useful when working with form data or setting a specific date in code.
Syntax
mktime(hour, minute, second, month, day, year)
Example
This example combines mktime() and date() to display a known date in a friendly format.
// Create a timestamp for October 3, 1975
$birthday = mktime(0, 0, 0, 10, 3, 1975);
// Format it as a readable string
echo date("l, F jS, Y", $birthday);
// Output: Friday, October 3rd, 1975
getdate()
If you need to break down a timestamp into labeled parts — like month, weekday, or hour — PHP offers the getdate() function.
The getdate() function returns a full breakdown of a timestamp as an associative array — ideal for displaying or processing individual parts like month, year, or day of the week.
$dateArray = getdate(mktime(0, 0, 0, 12, 25, 2025));
echo $dateArray['weekday']; // Output: Thursday
This function is especially helpful when you need to dynamically label calendar views or build custom logic based on the day, month, or time.
| Key | Description | Example |
|---|---|---|
| hours | Hour (0–23) | 14 |
| mday | Day of month | 21 |
| mon | Month (1–12) | 8 |
| year | Year (4 digits) | 2025 |
| weekday | Day of week (text) | Thursday |
📆 Calculating Days Between Dates
Using strtotime() with additional functions like date() and date('z') (day of the year), you can perform simple calendar math. These examples show how to calculate future dates or determine how many days remain until a given holiday.
// Calculate the number of days until a specific holiday
$holiday = date('z', strtotime("July 04"));
$today = date('z');
if ($holiday == $today) {
echo "Happy holiday!";
} elseif ($holiday > $today) {
echo "There are " . ($holiday - $today) . " days until holiday.";
} else {
$endOfYear = date('z', strtotime("December 31"));
$nextYear = date('z', strtotime("July 04 +1 year"));
$diff = ($endOfYear - $today) + $nextYear;
echo "There are $diff days until next year's holiday.";
}
⏱ Understanding DateTime
The DateTime class in PHP offers a powerful way to work with dates and times using an object-oriented approach. Unlike simple timestamps, a DateTime object includes both the date/time value and the timezone. It also provides built-in methods for formatting, comparing, and modifying dates. Think of it as an all-in-one toolkit for handling date/time operations more clearly and flexibly.
date_create()
Creates a DateTime object from a string (e.g., from user input).
$dt = date_create("2025-12-25 10:30:00");
Once created, you can format or manipulate the object using date_format(), modify(), or extract a timestamp using date_timestamp_get():
date_format()
Formats a DateTime object using the same formatting characters as date().
$dt = date_create("2025-12-25 10:30:00");
echo date_format($dt, "l, F jS, Y g:i A");
// Output: Thursday, December 25th, 2025 10:30 AM
modify()
Modifies a DateTime object using relative phrases.
Note: The following examples use PHP's object-oriented syntax with the -> operator. This lets you call methods on a DateTime object, like $dt->modify(). If this is new to you, don't worry — it simply means “run this method on this object.”
$dt = date_create("2025-12-25");
$dt->modify("+1 week");
echo date_format($dt, "Y-m-d");
// Output: 2026-01-01
date_timestamp_get()
Extracts a Unix timestamp from a DateTime object.
$dt = date_create("2025-12-25");
$timestamp = date_timestamp_get($dt);
echo $timestamp;
📆 Calculating Days Between Dates with DateTime
The DateTime class makes it easy to calculate the number of days between two dates using built-in object methods. This approach is more readable and accurate for edge cases like leap years. It also avoids manual math by returning a DateInterval object that includes the total number of days between the two dates.
// Create a DateTime object for today
$today = new DateTime();
// Create a DateTime object for the next July 4
$holiday = new DateTime(date("Y") . "-07-04");
// If the holiday has already passed this year, move to next year
if ($today > $holiday) {
$holiday->modify('+1 year');
}
// Use diff() to get the interval between the two dates
$interval = $today->diff($holiday);
// Output the number of days remaining
echo "There are " . $interval->days . " days until the holiday.";
Helpful Resources
- W3 Schools web site – Good beginner explanations.
- SitePoint Tutorials – Includes info about MySQL timestamps.
- Official PHP Manual – Extensive developer documentation.
Last updated: July 25, 2025 at 6:16 PM