Skip to content

php_ref_date

Handling dates and times is a common requirement in web development. PHP provides powerful tools to get the current date and time, format them, perform calculations, and manage timezones.

Best Practice: While PHP offers procedural functions like date(), time(), and strtotime(), it is strongly recommended to use the object-oriented DateTimeImmutable, DateTime, DateInterval, and DateTimeZone classes for modern PHP development. They offer better consistency, timezone handling, and avoid common pitfalls associated with timestamp manipulation.

Using DateTimeImmutable is generally preferred over DateTime because it creates new objects for modifications, preventing accidental changes to the original date object, which helps avoid bugs in complex applications.

Note: All date and time operations are dependent on the server’s default timezone setting unless explicitly specified. It’s crucial to set a default timezone for your application.

The core date and time functions and classes are part of the PHP engine. No installation is required.

It’s essential to set a default timezone for your application to ensure consistency. This can be done in php.ini or at runtime using date_default_timezone_set().

In php.ini:

date.timezone = "UTC"

Or at the beginning of your script:

<?php
date_default_timezone_set('UTC'); // Recommended: Use UTC or your application's primary timezone
?>

Failing to set a timezone will result in PHP emitting warnings and relying on the server’s system timezone, which might not be what you expect.

Here’s a basic example using DateTimeImmutable:

<?php
date_default_timezone_set('Europe/London');
// Create a new DateTimeImmutable object for the current time
$now = new DateTimeImmutable();
echo $now->format('Y-m-d H:i:s'); // Outputs current date and time in London
// Create from a specific string and format
$dateString = '2023-10-26 14:30:00';
$specificDate = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dateString);
echo "\n" . $specificDate->format(DateTimeInterface::RFC3339); // Outputs in standard format
// Modify the date (creates a NEW object)
$oneWeekLater = $specificDate->modify('+1 week');
echo "\nOne week later: " . $oneWeekLater->format('Y-m-d');
// Calculate difference between two dates
$interval = $now->diff($oneWeekLater);
echo "\nDifference: " . $interval->format('%R%a days'); // %R is sign, %a is total days
// Working with timezones
$tokyoTime = $now->setTimezone(new DateTimeZone('Asia/Tokyo'));
echo "\nCurrent time in Tokyo: " . $tokyoTime->format('Y-m-d H:i:s P');
?>

Key Concepts:

  • new DateTimeImmutable(): Creates an object for the current time.
  • DateTimeImmutable::createFromFormat(): Creates an object from a string matching a specific format.
  • format(): Outputs the date/time according to specified format characters (see PHP docs for options).
  • modify(): Returns a new DateTimeImmutable object with the modification applied.
  • diff(): Calculates the difference between two DateTimeInterface objects, returning a DateInterval object.
  • setTimezone(): Returns a new DateTimeImmutable object representing the same point in time but in a different timezone.

While the OO approach is preferred, you might encounter these functions in older codebases or for very simple tasks:

FunctionDescription (Legacy)
date()Formats a local date and time based on a timestamp.
time()Returns the current Unix timestamp (seconds since Jan 1 1970 UTC).
strtotime()Parses an English textual datetime description into a Unix timestamp. Can be ambiguous and locale-dependent.
mktime() / gmmktime()Gets Unix timestamp for a specific date (local/GMT).
getdate()Gets date/time information as an associative array from a timestamp.
checkdate()Validates a Gregorian date.

Example using date():

<?php
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s'); // Outputs current UTC time
// Get timestamp for a specific date (less reliable than DateTime)
$timestamp = strtotime('2023-12-25 00:00:00');
if ($timestamp !== false) {
echo "\nChristmas 2023: " . date('l, F jS, Y', $timestamp);
}
?>

Common Pitfall: Relying heavily on strtotime() can lead to unexpected results due to ambiguity in date formats (e.g., m/d/y vs d/m/y) and locale settings. DateTimeImmutable::createFromFormat() provides explicit control.

PHP provides predefined constants for common date formats, usable with DateTimeInterface::format().

ConstantDescription (Example Format)
DateTimeInterface::ATOM (formerly DATE_ATOM)Atom (e.g., 2023-10-26T15:04:05+01:00)
DateTimeInterface::COOKIE (formerly DATE_COOKIE)HTTP Cookies (e.g., Thursday, 26-Oct-2023 15:04:05 GMT)
DateTimeInterface::ISO8601 (formerly DATE_ISO8601)ISO-8601 (e.g., 2023-10-26T15:04:05+0100) - Note: Different from RFC3339
DateTimeInterface::RFC822 (formerly DATE_RFC822)RFC 822 (e.g., Thu, 26 Oct 23 15:04:05 +0100)
DateTimeInterface::RFC3339RFC 3339 (e.g., 2023-10-26T15:04:05+01:00) - Often preferred for APIs
DateTimeInterface::RFC3339_EXTENDEDRFC 3339 Extended Format (e.g., 2023-10-26T15:04:05.123+01:00)
DateTimeInterface::RSS (formerly DATE_RSS)RSS (e.g., Thu, 26 Oct 2023 15:04:05 +0100)
DateTimeInterface::W3C (formerly DATE_W3C)World Wide Web Consortium (e.g., 2023-10-26T15:04:05+01:00)

Example:

<?php
$now = new DateTimeImmutable();
echo $now->format(DateTimeInterface::RFC3339);
?>