PHP Dates & Time
PHP's date() function formats the current date and time (or a given timestamp) into a readable string using format characters like Y for a 4-digit year, m for month, and d for day.
For more advanced date handling, PHP provides the DateTime class, which supports comparing dates, adding intervals, and formatting output in an object-oriented way.
date("Y-m-d");
$dt = new DateTime();Using date()
date("Y-m-d") returns the current date in year-month-day format, and time() returns the current Unix timestamp, which date() can also format if passed as a second argument.
Using DateTime
new DateTime() creates a date object that can be modified with ->modify() and compared or formatted with ->format(), offering more flexibility than plain date().
<?php
echo date("Y-m-d");
?>2024-05-10date("Y-m-d") formats today's date as a 4-digit year, 2-digit month and day.
<?php
$dt = new DateTime("2024-01-01");
$dt->modify("+1 month");
echo $dt->format("Y-m-d");
?>2024-02-01DateTime lets you modify a date with a relative expression and format the result.
Key points
- date() formats the current time or a timestamp into a readable string.
- Y, m and d are common format characters for year, month and day.
- The DateTime class provides object-oriented date handling.
- ->modify() lets you add or subtract time intervals from a DateTime object.
