Skip to content

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

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 ago

Formats a timestamp (or current time) into a readable string.

// Current date and time
echo date('Y-m-d'); // 2024-12-19
echo date('H:i:s'); // 14:30:45
echo 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-19
// 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, 2024

CharacterDescriptionExample
Year
Y4-digit year2024
y2-digit year24
Month
mMonth (01-12)01, 12
nMonth (1-12)1, 12
FFull month nameJanuary
MShort month nameJan
Day
dDay (01-31)01, 31
jDay (1-31)1, 31
lFull day nameMonday
DShort day nameMon
Time
HHour 24-format (00-23)00, 23
hHour 12-format (01-12)01, 12
iMinutes (00-59)00, 59
sSeconds (00-59)00, 59
AAM/PMAM, PM
aam/pmam, pm
Other
UUnix timestamp1703001600
NDay of week (1-7)1 (Monday)
wDay of week (0-6)0 (Sunday)
WWeek number51
tDays in month28, 31
$date = new DateTime('2024-12-19 14:30:45');
// Database format
echo $date->format('Y-m-d H:i:s'); // 2024-12-19 14:30:45
// Human-readable formats
echo $date->format('F j, Y'); // December 19, 2024
echo $date->format('l, F j, Y'); // Thursday, December 19, 2024
echo $date->format('M j, Y g:i A'); // Dec 19, 2024 2:30 PM
// ISO 8601 format
echo $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 formats
echo $date->format('d/m/Y'); // 19/12/2024
echo $date->format('m-d-Y'); // 12-19-2024

strtotime() - Parse English Text to Timestamp

Section titled “strtotime() - Parse English Text to Timestamp”

Converts date/time strings into Unix timestamps.

// Absolute dates
echo strtotime('2024-12-25'); // Unix timestamp
echo strtotime('December 25, 2024'); // Same result
echo strtotime('25 December 2024'); // Same result
// Relative dates (from current time)
echo strtotime('now'); // Current timestamp
echo strtotime('today'); // Today at midnight
echo strtotime('tomorrow'); // Tomorrow at midnight
echo strtotime('yesterday'); // Yesterday at midnight
// Relative adjustments
echo strtotime('+1 day'); // Tomorrow
echo strtotime('+1 week'); // 7 days from now
echo strtotime('+2 weeks 3 days'); // 17 days from now
echo strtotime('-1 month'); // 1 month ago
echo strtotime('+1 year'); // 1 year from now
// Time adjustments
echo strtotime('+3 hours'); // 3 hours from now
echo strtotime('-30 minutes'); // 30 minutes ago
// Specific day references
echo strtotime('next Monday'); // Next Monday
echo strtotime('last Friday'); // Last Friday
echo strtotime('first day of next month'); // First of next month
echo strtotime('last day of this month'); // Last day of current month
// Combining with date()
echo date('Y-m-d', strtotime('+1 week')); // 2024-12-26
echo date('Y-m-d', strtotime('next Monday')); // Next Monday's date

DateTime::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, 2024
echo $date2->format('F j, Y'); // December 19, 2024
echo $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')
);

// 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 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)
$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 components
echo $date->format('Y'); // Year
echo $date->format('m'); // Month
echo $date->format('d'); // Day
$date1 = new DateTime('2024-12-19');
$date2 = new DateTime('2024-12-25');
// Direct comparison
if ($date1 < $date2) {
echo "Date1 is earlier";
}
if ($date1 == $date2) {
echo "Dates are equal";
}
if ($date1 > $date2) {
echo "Date1 is later";
}
// Compare timestamps
if ($date1->getTimestamp() < $date2->getTimestamp()) {
echo "Date1 is earlier";
}

// 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-29

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]S
$date = new DateTime('2024-12-19');
// Add time
$date->add(new DateInterval('P10D')); // Add 10 days
echo $date->format('Y-m-d'); // 2024-12-29
// Subtract time
$date->sub(new DateInterval('P1M')); // Subtract 1 month
echo $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-24
$date1 = new DateTime('2024-01-01');
$date2 = new DateTime('2024-12-25');
$diff = $date1->diff($date2);
echo $diff->days; // Total days: 359
echo $diff->y; // Years: 0
echo $diff->m; // Months: 11
echo $diff->d; // Days: 24
// Format the difference
echo $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 future
if ($diff->invert === 1) {
echo "Date1 is after Date2";
} else {
echo "Date1 is before Date2";
}

// Set default timezone for all date functions
date_default_timezone_set('America/New_York');
// Get current timezone
echo date_default_timezone_get(); // America/New_York
// 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 offset
echo $nyTz->getOffset($date) / 3600; // -5 (hours from UTC)
// 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 JST
// Get all timezone identifiers
$timezones = DateTimeZone::listIdentifiers();
// Get timezones by region
$usTimezones = DateTimeZone::listIdentifiers(DateTimeZone::AMERICA);
$euroTimezones = DateTimeZone::listIdentifiers(DateTimeZone::EUROPE);

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 version
function 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
];
}
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')); // true
var_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')); // true
// 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 dates
function 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);
}
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');
}
}
// 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'));

FunctionPurposeExample
time()Current timestamptime()
date($format, $ts)Format timestampdate('Y-m-d')
strtotime($str)Parse to timestampstrtotime('+1 week')
mktime(...)Create timestampmktime(12, 0, 0, 12, 25, 2024)
checkdate($m, $d, $y)Validate datecheckdate(12, 25, 2024)
MethodPurpose
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
P[n]Y[n]M[n]DT[n]H[n]M[n]S
P = Period (required)
nY = Years
nM = Months
nD = Days
T = Time separator (required before time components)
nH = Hours
nM = Minutes
nS = Seconds
Examples:
P1D = 1 day
P2W = 2 weeks
P1M = 1 month
PT1H = 1 hour
P1Y2M3DT4H5M6S = 1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds