PHP ยท Chapter 27 of 44

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.

Syntax
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().

Example 1 (php)
<?php
  echo date("Y-m-d");
?>
Output
2024-05-10

date("Y-m-d") formats today's date as a 4-digit year, 2-digit month and day.

Example 2 (php)
<?php
  $dt = new DateTime("2024-01-01");
  $dt->modify("+1 month");
  echo $dt->format("Y-m-d");
?>
Output
2024-02-01

DateTime 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.
๐Ÿ’ก Note: Always set your script's timezone with date_default_timezone_set() to avoid unexpected date/time results.

๐Ÿ“ Quick Quiz

1. Which function formats the current date as a string?

2. What does the format character 'Y' represent?

3. Which class provides object-oriented date handling in PHP?