PHP Date and Time

PHP Date and Time

PHP's date functions let you format timestamps, parse date strings, and perform date arithmetic.

1 - Current Date and Time

echo date("Y-m-d");           // 2024-05-01
echo date("d/m/Y");           // 01/05/2024
echo date("l, F j, Y");       // Wednesday, May 1, 2024
echo date("H:i:s");           // 14:30:00
echo date("D, d M Y H:i:s T"); // Wed, 01 May 2024 14:30:00 UTC

2 - Format Characters

  • Y / y — 4-digit / 2-digit year
  • m / n — month with / without leading zero
  • d / j — day with / without leading zero
  • H / h — 24h / 12h hour
  • i — minutes, s — seconds
  • l — full day name, D — short day name
  • F — full month name, M — short month name

3 - strtotime() and mktime()

strtotime("next Monday");         // timestamp
strtotime("+30 days");            // 30 days from now
strtotime("2024-12-25");          // Christmas 2024

$ts = mktime(12, 0, 0, 6, 15, 2024); // June 15 2024 12:00
echo date("Y-m-d H:i", $ts);

4 - DateTime Class (OOP)

$dt = new DateTime();
echo $dt->format("Y-m-d H:i:s");

$dt = new DateTime("2024-01-01");
$dt->modify("+6 months");
echo $dt->format("Y-m-d"); // 2024-07-01

// Date diff
$start = new DateTime("2024-01-01");
$end   = new DateTime("2024-12-31");
$diff  = $start->diff($end);
echo $diff->days . " days"; // 365 days

Note: Always set your default timezone. Add date_default_timezone_set("UTC") to your bootstrap file, or set date.timezone = UTC in php.ini to avoid inconsistent results across servers.

-Tip-