PHP Date and Time
PHP provides powerful functions for working with dates and times. The date() function formats a Unix timestamp, while the DateTime class offers an OOP approach.
date(), time(), and mktime()
time() returns the current Unix timestamp (seconds since Jan 1, 1970). date() formats it using format characters.
<?php
$now = time(); // Unix timestamp
// Format characters
echo date("Y"); // 2024 (4-digit year)
echo date("m"); // 01-12 (month)
echo date("d"); // 01-31 (day)
echo date("H"); // 00-23 (hour)
echo date("i"); // 00-59 (minutes)
echo date("s"); // 00-59 (seconds)
echo date("D"); // Mon, Tue... (short day)
echo date("l"); // Monday, Tuesday... (full day)
echo date("N"); // 1=Mon ... 7=Sun
echo date("t"); // days in current month
// Common formats
echo date("Y-m-d"); // 2024-01-15
echo date("d/m/Y"); // 15/01/2024
echo date("D, d M Y H:i:s"); // Mon, 15 Jan 2024 14:30:00
echo date("r"); // RFC 2822 formatted date
// mktime — create timestamp for specific date
$ts = mktime(12, 0, 0, 6, 15, 2024); // noon on June 15, 2024
echo date("Y-m-d H:i:s", $ts); // 2024-06-15 12:00:00
?>
strtotime() — Parse Date Strings
strtotime() converts a human-readable date string into a Unix timestamp. It supports relative expressions like "next Monday" or "+1 week".
<?php
echo date("Y-m-d", strtotime("2024-01-15")); // 2024-01-15
echo date("Y-m-d", strtotime("next Monday")); // next Monday's date
echo date("Y-m-d", strtotime("+1 week")); // 7 days from now
echo date("Y-m-d", strtotime("+1 month")); // 1 month from now
echo date("Y-m-d", strtotime("-1 year")); // 1 year ago
echo date("Y-m-d", strtotime("last day of this month")); // end of month
?>
DateTime Class
The DateTime class provides an OOP interface for date manipulation, including date arithmetic with DateInterval.
<?php
// Create DateTime objects
$now = new DateTime();
$birth = new DateTime("1995-06-15");
// Format
echo $now->format("Y-m-d H:i:s");
// Modify
$now->modify("+30 days");
echo $now->format("Y-m-d");
// Date difference
$diff = $now->diff($birth);
echo $diff->y . " years, " . $diff->m . " months, " . $diff->d . " days";
// DateTimeImmutable — does not modify original
$date = new DateTimeImmutable("2024-01-01");
$next = $date->modify("+1 year"); // returns new object
echo $date->format("Y"); // 2024 (unchanged)
echo $next->format("Y"); // 2025
// Create from format
$d = DateTime::createFromFormat("d/m/Y", "25/12/2024");
echo $d->format("Y-m-d"); // 2024-12-25
?>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.