Date & Time Functions
PHP provides powerful tools for working with dates and times, from simple procedural functions to the robust DateTime class. This guide covers both approaches.
PHP Date/Time Functions - Full Documentation ↗
Getting Current Date & Time
Section titled “Getting Current Date & Time”time() - Get Unix Timestamp
Section titled “time() - Get Unix Timestamp”Returns the current Unix timestamp (seconds since January 1, 1970).
$timestamp = time();echo $timestamp; // e.g., 1703001600
// Useful for comparisons and calculations$futureTime = time() + 3600; // 1 hour from now$pastTime = time() - 86400; // 24 hours agodate() - Format Current Date/Time
Section titled “date() - Format Current Date/Time”Formats a timestamp (or current time) into a readable string.
// Current date and timeecho date('Y-m-d'); // 2024-12-19echo date('H:i:s'); // 14:30:45echo date('Y-m-d H:i:s'); // 2024-12-19 14:30:45
// Format a specific timestamp$timestamp = 1703001600;echo date('Y-m-d', $timestamp); // 2023-12-19DateTime Class - Object-Oriented Approach
Section titled “DateTime Class - Object-Oriented Approach”// Current date and time$now = new DateTime();echo $now->format('Y-m-d H:i:s'); // 2024-12-19 14:30:45
// Specific date$date = new DateTime('2024-12-25');echo $date->format('l, F j, Y'); // Wednesday, December 25, 2024Date Format Characters
Section titled “Date Format Characters”Common Format Characters
Section titled “Common Format Characters”| Character | Description | Example |
|---|---|---|
| Year | ||
Y | 4-digit year | 2024 |
y | 2-digit year | 24 |
| Month | ||
m | Month (01-12) | 01, 12 |
n | Month (1-12) | 1, 12 |
F | Full month name | January |
M | Short month name | Jan |
| Day | ||
d | Day (01-31) | 01, 31 |
j | Day (1-31) | 1, 31 |
l | Full day name | Monday |
D | Short day name | Mon |
| Time | ||
H | Hour 24-format (00-23) | 00, 23 |
h | Hour 12-format (01-12) | 01, 12 |
i | Minutes (00-59) | 00, 59 |
s | Seconds (00-59) | 00, 59 |
A | AM/PM | AM, PM |
a | am/pm | am, pm |
| Other | ||
U | Unix timestamp | 1703001600 |
N | Day of week (1-7) | 1 (Monday) |
w | Day of week (0-6) | 0 (Sunday) |
W | Week number | 51 |
t | Days in month | 28, 31 |
Common Format Patterns
Section titled “Common Format Patterns”$date = new DateTime('2024-12-19 14:30:45');
// Database formatecho $date->format('Y-m-d H:i:s'); // 2024-12-19 14:30:45
// Human-readable formatsecho $date->format('F j, Y'); // December 19, 2024echo $date->format('l, F j, Y'); // Thursday, December 19, 2024echo $date->format('M j, Y g:i A'); // Dec 19, 2024 2:30 PM
// ISO 8601 formatecho $date->format('c'); // 2024-12-19T14:30:45+00:00
// RFC 2822 (email dates)echo $date->format('r'); // Thu, 19 Dec 2024 14:30:45 +0000
// Custom formatsecho $date->format('d/m/Y'); // 19/12/2024echo $date->format('m-d-Y'); // 12-19-2024Parsing Dates
Section titled “Parsing Dates”strtotime() - Parse English Text to Timestamp
Section titled “strtotime() - Parse English Text to Timestamp”Converts date/time strings into Unix timestamps.
// Absolute datesecho strtotime('2024-12-25'); // Unix timestampecho strtotime('December 25, 2024'); // Same resultecho strtotime('25 December 2024'); // Same result
// Relative dates (from current time)echo strtotime('now'); // Current timestampecho strtotime('today'); // Today at midnightecho strtotime('tomorrow'); // Tomorrow at midnightecho strtotime('yesterday'); // Yesterday at midnight
// Relative adjustmentsecho strtotime('+1 day'); // Tomorrowecho strtotime('+1 week'); // 7 days from nowecho strtotime('+2 weeks 3 days'); // 17 days from nowecho strtotime('-1 month'); // 1 month agoecho strtotime('+1 year'); // 1 year from now
// Time adjustmentsecho strtotime('+3 hours'); // 3 hours from nowecho strtotime('-30 minutes'); // 30 minutes ago
// Specific day referencesecho strtotime('next Monday'); // Next Mondayecho strtotime('last Friday'); // Last Fridayecho strtotime('first day of next month'); // First of next monthecho strtotime('last day of this month'); // Last day of current month
// Combining with date()echo date('Y-m-d', strtotime('+1 week')); // 2024-12-26echo date('Y-m-d', strtotime('next Monday')); // Next Monday's dateDateTime::createFromFormat() - Parse with Specific Format
Section titled “DateTime::createFromFormat() - Parse with Specific Format”Parse dates with a known format (more reliable than strtotime()).
// Parse various formats$date1 = DateTime::createFromFormat('Y-m-d', '2024-12-19');$date2 = DateTime::createFromFormat('d/m/Y', '19/12/2024');$date3 = DateTime::createFromFormat('m-d-Y H:i', '12-19-2024 14:30');
echo $date1->format('F j, Y'); // December 19, 2024echo $date2->format('F j, Y'); // December 19, 2024echo $date3->format('F j, Y g:i A'); // December 19, 2024 2:30 PM
// Handle parsing errors$date = DateTime::createFromFormat('Y-m-d', 'invalid-date');if ($date === false) { $errors = DateTime::getLastErrors(); print_r($errors); // Shows parsing errors}
// Parse with timezone$date = DateTime::createFromFormat( 'Y-m-d H:i:s', '2024-12-19 14:30:00', new DateTimeZone('America/New_York'));DateTime Class (Modern Approach)
Section titled “DateTime Class (Modern Approach)”Creating DateTime Objects
Section titled “Creating DateTime Objects”// Current date/time$now = new DateTime();
// From string$date1 = new DateTime('2024-12-25');$date2 = new DateTime('2024-12-25 14:30:00');$date3 = new DateTime('next Monday');$date4 = new DateTime('+1 week');
// From timestamp$date = new DateTime();$date->setTimestamp(1703001600);
// With timezone$date = new DateTime('now', new DateTimeZone('Europe/London'));DateTime vs DateTimeImmutable
Section titled “DateTime vs DateTimeImmutable”DateTime modifies the object in place, while DateTimeImmutable returns a new object.
// DateTime - modifies original$date = new DateTime('2024-12-19');$date->modify('+1 day');echo $date->format('Y-m-d'); // 2024-12-20 (original changed)
// DateTimeImmutable - returns new object$date = new DateTimeImmutable('2024-12-19');$newDate = $date->modify('+1 day');echo $date->format('Y-m-d'); // 2024-12-19 (unchanged)echo $newDate->format('Y-m-d'); // 2024-12-20 (new object)Modifying Dates
Section titled “Modifying Dates”$date = new DateTime('2024-12-19');
// Using modify() - accepts strtotime() strings$date->modify('+1 day');$date->modify('+2 weeks');$date->modify('next Monday');
// Using setDate(), setTime()$date->setDate(2024, 12, 25); // Set to Dec 25, 2024$date->setTime(14, 30, 0); // Set to 2:30 PM
// Get individual componentsecho $date->format('Y'); // Yearecho $date->format('m'); // Monthecho $date->format('d'); // DayComparing Dates
Section titled “Comparing Dates”$date1 = new DateTime('2024-12-19');$date2 = new DateTime('2024-12-25');
// Direct comparisonif ($date1 < $date2) { echo "Date1 is earlier";}
if ($date1 == $date2) { echo "Dates are equal";}
if ($date1 > $date2) { echo "Date1 is later";}
// Compare timestampsif ($date1->getTimestamp() < $date2->getTimestamp()) { echo "Date1 is earlier";}Date Arithmetic
Section titled “Date Arithmetic”Using strtotime() for Simple Calculations
Section titled “Using strtotime() for Simple Calculations”// Add/subtract time$nextWeek = date('Y-m-d', strtotime('+1 week'));$lastMonth = date('Y-m-d', strtotime('-1 month'));
// From a specific date$baseDate = '2024-12-19';$future = date('Y-m-d', strtotime($baseDate . ' +10 days'));echo $future; // 2024-12-29DateInterval Class
Section titled “DateInterval Class”Represents a duration of time.
// Create intervals$interval1 = new DateInterval('P1D'); // 1 day$interval2 = new DateInterval('P2W'); // 2 weeks$interval3 = new DateInterval('P1M'); // 1 month$interval4 = new DateInterval('P1Y'); // 1 year$interval5 = new DateInterval('PT1H'); // 1 hour$interval6 = new DateInterval('PT30M'); // 30 minutes$interval7 = new DateInterval('P1Y2M3D'); // 1 year, 2 months, 3 days$interval8 = new DateInterval('P1DT12H'); // 1 day, 12 hours
// Interval format: P[years]Y[months]M[days]DT[hours]H[minutes]M[seconds]SDateTime::add() and DateTime::sub()
Section titled “DateTime::add() and DateTime::sub()”$date = new DateTime('2024-12-19');
// Add time$date->add(new DateInterval('P10D')); // Add 10 daysecho $date->format('Y-m-d'); // 2024-12-29
// Subtract time$date->sub(new DateInterval('P1M')); // Subtract 1 monthecho $date->format('Y-m-d'); // 2024-11-29
// Chain operations (with DateTimeImmutable)$date = new DateTimeImmutable('2024-12-19');$result = $date ->add(new DateInterval('P1M')) ->add(new DateInterval('P5D'));echo $result->format('Y-m-d'); // 2025-01-24DateTime::diff() - Calculate Differences
Section titled “DateTime::diff() - Calculate Differences”$date1 = new DateTime('2024-01-01');$date2 = new DateTime('2024-12-25');
$diff = $date1->diff($date2);
echo $diff->days; // Total days: 359echo $diff->y; // Years: 0echo $diff->m; // Months: 11echo $diff->d; // Days: 24
// Format the differenceecho $diff->format('%y years, %m months, %d days');// Output: 0 years, 11 months, 24 days
echo $diff->format('%a total days');// Output: 359 total days
// Check if date is in past or futureif ($diff->invert === 1) { echo "Date1 is after Date2";} else { echo "Date1 is before Date2";}Timezone Handling
Section titled “Timezone Handling”Setting Default Timezone
Section titled “Setting Default Timezone”// Set default timezone for all date functionsdate_default_timezone_set('America/New_York');
// Get current timezoneecho date_default_timezone_get(); // America/New_YorkDateTimeZone Class
Section titled “DateTimeZone Class”// Create timezone objects$nyTz = new DateTimeZone('America/New_York');$londonTz = new DateTimeZone('Europe/London');$tokyoTz = new DateTimeZone('Asia/Tokyo');
// Create date with specific timezone$date = new DateTime('now', $nyTz);echo $date->format('Y-m-d H:i:s T'); // 2024-12-19 09:30:00 EST
// Get timezone offsetecho $nyTz->getOffset($date) / 3600; // -5 (hours from UTC)Converting Between Timezones
Section titled “Converting Between Timezones”// Create a date in New York timezone$nyDate = new DateTime('2024-12-19 14:00:00', new DateTimeZone('America/New_York'));echo $nyDate->format('Y-m-d H:i:s T'); // 2024-12-19 14:00:00 EST
// Convert to London timezone$nyDate->setTimezone(new DateTimeZone('Europe/London'));echo $nyDate->format('Y-m-d H:i:s T'); // 2024-12-19 19:00:00 GMT
// Convert to Tokyo timezone$nyDate->setTimezone(new DateTimeZone('Asia/Tokyo'));echo $nyDate->format('Y-m-d H:i:s T'); // 2024-12-20 04:00:00 JSTList Available Timezones
Section titled “List Available Timezones”// Get all timezone identifiers$timezones = DateTimeZone::listIdentifiers();
// Get timezones by region$usTimezones = DateTimeZone::listIdentifiers(DateTimeZone::AMERICA);$euroTimezones = DateTimeZone::listIdentifiers(DateTimeZone::EUROPE);Practical Examples
Section titled “Practical Examples”Age Calculation
Section titled “Age Calculation”function calculateAge(string $birthdate): int { $birth = new DateTime($birthdate); $today = new DateTime('today'); $age = $birth->diff($today); return $age->y;}
echo calculateAge('1990-05-15'); // e.g., 34
// More detailed versionfunction getAgeDetails(string $birthdate): array { $birth = new DateTime($birthdate); $today = new DateTime('today'); $diff = $birth->diff($today);
return [ 'years' => $diff->y, 'months' => $diff->m, 'days' => $diff->d, 'total_days' => $diff->days ];}Date Validation
Section titled “Date Validation”function isValidDate(string $date, string $format = 'Y-m-d'): bool { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) === $date;}
var_dump(isValidDate('2024-12-19')); // truevar_dump(isValidDate('2024-13-19')); // false (invalid month)var_dump(isValidDate('2024-02-30')); // false (invalid day)var_dump(isValidDate('19/12/2024', 'd/m/Y')); // trueWorking with Database Dates
Section titled “Working with Database Dates”// Storing to database (MySQL DATETIME format)$date = new DateTime();$dbFormat = $date->format('Y-m-d H:i:s');// Use in INSERT: ... VALUES ('$dbFormat')
// Reading from database$dbDate = '2024-12-19 14:30:00';$date = new DateTime($dbDate);echo $date->format('F j, Y g:i A'); // December 19, 2024 2:30 PM
// Handle NULL datesfunction formatDbDate(?string $dbDate, string $format = 'M j, Y'): string { if ($dbDate === null || $dbDate === '0000-00-00') { return 'N/A'; } return (new DateTime($dbDate))->format($format);}Formatting for Display
Section titled “Formatting for Display”function formatDateForDisplay(string $date, string $style = 'medium'): string { $dt = new DateTime($date);
return match($style) { 'short' => $dt->format('m/d/Y'), // 12/19/2024 'medium' => $dt->format('M j, Y'), // Dec 19, 2024 'long' => $dt->format('F j, Y'), // December 19, 2024 'full' => $dt->format('l, F j, Y'), // Thursday, December 19, 2024 'datetime' => $dt->format('M j, Y g:i A'), // Dec 19, 2024 2:30 PM 'relative' => getRelativeTime($dt), default => $dt->format('Y-m-d') };}
function getRelativeTime(DateTime $date): string { $now = new DateTime(); $diff = $now->diff($date);
if ($diff->days === 0) { return 'Today'; } elseif ($diff->days === 1 && $diff->invert === 1) { return 'Yesterday'; } elseif ($diff->days === 1 && $diff->invert === 0) { return 'Tomorrow'; } elseif ($diff->days < 7) { return $diff->invert ? "{$diff->days} days ago" : "In {$diff->days} days"; } else { return $date->format('M j, Y'); }}Date Range Iteration
Section titled “Date Range Iteration”// Iterate through a date range$start = new DateTime('2024-12-01');$end = new DateTime('2024-12-07');$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) { echo $date->format('Y-m-d') . "\n";}// Output: 2024-12-01 through 2024-12-06
// Include end date$period = new DatePeriod($start, $interval, $end->modify('+1 day'));Quick Reference
Section titled “Quick Reference”Common Functions
Section titled “Common Functions”| Function | Purpose | Example |
|---|---|---|
time() | Current timestamp | time() |
date($format, $ts) | Format timestamp | date('Y-m-d') |
strtotime($str) | Parse to timestamp | strtotime('+1 week') |
mktime(...) | Create timestamp | mktime(12, 0, 0, 12, 25, 2024) |
checkdate($m, $d, $y) | Validate date | checkdate(12, 25, 2024) |
DateTime Methods
Section titled “DateTime Methods”| Method | Purpose |
|---|---|
format($format) | Format as string |
modify($str) | Modify date |
add($interval) | Add interval |
sub($interval) | Subtract interval |
diff($date) | Calculate difference |
setTimezone($tz) | Change timezone |
getTimestamp() | Get Unix timestamp |
setTimestamp($ts) | Set from timestamp |
DateInterval Format
Section titled “DateInterval Format”P[n]Y[n]M[n]DT[n]H[n]M[n]S
P = Period (required)nY = YearsnM = MonthsnD = DaysT = Time separator (required before time components)nH = HoursnM = MinutesnS = Seconds
Examples:P1D = 1 dayP2W = 2 weeksP1M = 1 monthPT1H = 1 hourP1Y2M3DT4H5M6S = 1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds