PHP: Math and Date Functions
Calculating discounts, building reports, displaying "posted 3 days ago," generating order numbers — math and date operations are essential to every web application.
1. Common Math Functions
PHP
<?php
// Basic operations
echo abs(-5); // 5 (absolute value)
echo ceil(3.14); // 4 (round up)
echo floor(3.99); // 3 (round down)
echo round(3.5); // 4 (rounds .5 to nearest even)
echo round(3.14159, 2); // 3.14 (2 decimal places)
// Min and max
echo max(3, 7, 2, 9); // 9 (maximum)
echo min(3, 7, 2, 9); // 2 (minimum)
echo max([5, 3, 9, 1]); // 9 (arrays work too)
// Powers and roots
echo pow(2, 3); // 8 (2 to the power of 3)
echo sqrt(16); // 4 (square root)
// Random numbers
echo rand(1, 100); // Random integer between 1 and 100
echo mt_rand(1, 1000); // High-quality random (recommended)
echo random_int(1, 10); // Cryptographically secure random (PHP 7+)
?>
💡 Tip: For everyday randomness, use
mt_rand() — it's about 4× faster and produces better randomness than rand(). For security-sensitive values like passwords and tokens, use random_int() instead, which is cryptographically secure.
2. The date() Function
date() is PHP's workhorse for formatting dates and times via a format string:
PHP
<?php
// Current date and time
echo date("Y-m-d"); // 2026-06-29
echo date("l, F j, Y"); // Monday, June 29, 2026
echo date("H:i:s"); // 14:30:45
echo date("Y-m-d H:i:s"); // 2026-06-29 14:30:45
// Day of week
echo date("l"); // Monday (full weekday name)
echo date("w"); // 1 (numeric day, 0 = Sunday)
?>
(1) Common Format Characters
| Character | Meaning | Example |
|---|---|---|
Y |
Four-digit year | 2026 |
y |
Two-digit year | 26 |
m |
Month (zero-padded) | 06 |
n |
Month (no padding) | 6 |
d |
Day (zero-padded) | 09 |
j |
Day (no padding) | 9 |
H |
24-hour (zero-padded) | 14 |
i |
Minutes (zero-padded) | 30 |
s |
Seconds (zero-padded) | 45 |
▶ Example: Timestamp Conversions
Output:
TEXT
📖 Display only
value
2024-01-15 10:30:00
2024-01-15 10:30:00
2024-01-15
2024-01-15
2024-01-15
2024-01-15
PHP
<?php
// time(): current Unix timestamp (seconds since January 1, 1970)
$now = time();
echo $now; // e.g. 1751101234
// date() accepts a timestamp as its second argument
echo date("Y-m-d H:i:s", $now);
// strtotime(): human-readable dates → timestamps
$ts = strtotime("2026-01-01 00:00:00");
echo date("F j, Y", $ts); // January 1, 2026
// strtotime is surprisingly smart
echo date("Y-m-d", strtotime("+1 week")); // One week from now
echo date("Y-m-d", strtotime("next Monday")); // Next Monday
echo date("Y-m-d", strtotime("last day of this month")); // Last day of this month
echo date("Y-m-d", strtotime("+3 months")); // Three months from now
?>
Output:
TEXT
📖 Display only
Output displayed
💡 Tip:
strtotime() understands natural-language phrases like +1 week, next Monday, and first day of next month. That said, don't lean on it for complex date math — use the DateTime class instead.
3. The DateTime Class
date() and strtotime() cover the simple cases. For anything more complex, reach for the DateTime class — it's object-oriented and far more powerful:
PHP
<?php
// Creating DateTime objects
$now = new DateTime();
$specific = new DateTime("2026-06-01 09:00:00");
$fromFormat = DateTime::createFromFormat("d/m/Y", "15/08/2026");
// Formatting output
echo $now->format("Y-m-d H:i:s");
// Adding and subtracting dates
$future = new DateTime();
$future->modify("+2 weeks");
$future->modify("+3 days");
echo $future->format("Y-m-d"); // Today + 17 days
// Calculating differences
$birthday = new DateTime("2000-01-15");
$today = new DateTime();
$diff = $birthday->diff($today);
echo "You have been alive for {$diff->days} days, {$diff->y} years";
// diff() returns a DateInterval object with y/m/d/h/i/s/days properties
?>
▶ Example: Date Comparison and Ranges
Output:
TEXT
📖 Display only
Start date is before end date
2024-01-15
PHP
<?php
$start = new DateTime("2026-06-01");
$end = new DateTime("2026-06-30");
// Comparing dates
if ($start < $end) {
echo "Start date is before end date";
}
// Iterating over a date range
$period = new DateInterval("P7D"); // 7-day interval
$dates = new DatePeriod($start, $period, $end);
foreach ($dates as $date) {
echo $date->format("m-d") . " ";
}
// Output: 06-01 06-08 06-15 06-22 06-29
?>
Output:
TEXT
📖 Display only
2024-01-15 10:30:00
result
4. Timezone Configuration
PHP
<?php
// Set the timezone (do this once at the top of your script)
date_default_timezone_set("Asia/Shanghai");
echo date("Y-m-d H:i:s"); // Now shows Shanghai time
// Check the current timezone
echo date_default_timezone_get(); // Asia/Shanghai
// Common timezones:
// Asia/Shanghai - China Standard Time (UTC+8)
// Asia/Tokyo - Japan Standard Time (UTC+9)
// Europe/London - Greenwich Mean Time / British Summer Time
// America/New_York - Eastern Time (UTC-5/UTC-4)
?>
⚠️ Warning: PHP's default timezone is UTC. If your site serves users in a specific region, always call
date_default_timezone_set() at the top of your script. Without it, timestamps on user comments might appear 8 hours off.
5. Real-World Date Recipes
PHP
<?php
// 1. Calculate age
function getAge(string $birthday): int {
$born = new DateTime($birthday);
$today = new DateTime();
return $born->diff($today)->y;
}
echo getAge("2000-01-15"); // 26
// 2. Display relative time ("posted 3 days ago")
function timeAgo(string $datetime): string {
$past = new DateTime($datetime);
$now = new DateTime();
$diff = $past->diff($now);
if ($diff->y > 0) return $diff->y . " year(s) ago";
if ($diff->m > 0) return $diff->m . " month(s) ago";
if ($diff->d > 0) return $diff->d . " day(s) ago";
if ($diff->h > 0) return $diff->h . " hour(s) ago";
if ($diff->i > 0) return $diff->i . " minute(s) ago";
return "just now";
}
// 3. Generate an order number
function generateOrderNo(): string {
return date("YmdHis") . mt_rand(1000, 9999);
}
echo generateOrderNo(); // 202606291430451234
?>
▶ Example: strtotime for Date Arithmetic
PHP
<?php
$today = date("Y-m-d");
echo "Today: {$today}<br>";
echo "Tomorrow: " . date("Y-m-d", strtotime("+1 day")) . "<br>";
echo "Next week: " . date("Y-m-d", strtotime("+1 week")) . "<br>";
echo "30 days ago: " . date("Y-m-d", strtotime("-30 days")) . "<br>";
echo "Next Friday: " . date("Y-m-d", strtotime("next Friday")) . "<br>";
Output:
TEXT
📖 Display only
Output displayed
❓ FAQ
Q
date() or DateTime — which should I use?A Use
date() for simple one-line formatting. Reach for DateTime when you need to calculate date differences, iterate over date ranges, modify dates, or compare them.Q Why is my time off by 8 hours?
A Timezone. Call
date_default_timezone_set("Asia/Shanghai") in your script (or set date.timezone = Asia/Shanghai in your php.ini).Q What does
strtotime("2026/02/29") return?A February 29 doesn't exist in 2026.
strtotime auto-corrects and returns 2026-03-01. DateTime handles this the same way.📖 Summary
abs,ceil,floor,round,max,min,pow,sqrtare the most-used math functionsmt_rand()for fast random numbers;random_int()for cryptographically secure valuesdate("Y-m-d H:i:s")formats date-time via format charactersstrtotime()converts human-readable phrases to timestamps- The
DateTimeclass handles complex date operations (diff, modify, comparison) - Always set your timezone:
date_default_timezone_set("Asia/Shanghai")
📝 Exercises
- Use
date()to output the current time in three different formats: ISO date (YYYY-MM-DD), a full human-readable format with weekday, and a compact 24-hour time. - Write a function
getDaysBetween($date1, $date2)that usesDateTimeto calculate the number of days between two dates. - Write a function
isWeekend($date)that returnstrueif the given date falls on a Saturday or Sunday.