PHP Date/Time

Beginner
10 min read
Updated: Nov 2026
3 examples
Dates, timezones & intervals

Definition and Usage

Date/Time support in PHP lets a script read the clock, parse dates from text, format them for people, move between timezones, and measure the gap between two moments. It is the base for blog post dates, booking forms, expiry checks, reports, and anything else that changes with time.

The quickest tools are time(), which returns the current Unix timestamp (seconds since 1970-01-01 00:00:00 UTC), date(), which turns a timestamp into text, and strtotime(), which turns text such as 2024-01-15 or +1 week into a timestamp.

For anything beyond a simple label, use the object API. DateTimeImmutable holds a date and time, DateTimeZone holds a timezone, and DateInterval holds a length of time. The procedural names such as date_create(), date_add(), and date_diff() are aliases that call the same code.

This page explains the ideas. The Date/Time Functions index lists all 51 function guides.

Pick the right tool.

Use date() with time() for a quick label. Use DateTimeImmutable when you need timezones, intervals, or comparison. Both read the same format characters.

Always know your timezone.

A timestamp is the same everywhere, but the text it produces depends on the timezone. Set it once with date_default_timezone_set() and read it back with date_default_timezone_get(), or pass a DateTimeZone to a single object.

strtotime() can return false.

Text that cannot be parsed gives false, not an error. Check with === false before you format the result, or use date_create_from_format() when you know the exact input format.

PHP Syntax

The usual set timezone, parse, format, and compare pattern:

PHP
date_default_timezone_set('UTC');           // set the default timezone once

$now = time();                              // int: current Unix timestamp
echo date('Y-m-d H:i:s', $now);             // format a timestamp

$ts = strtotime('2024-01-15 10:30:00');     // int, or false on bad text
echo date('D, d M Y', $ts);                 // Mon, 15 Jan 2024

$d = new DateTimeImmutable('2024-01-15');   // object style
$next = $d->modify('+1 month');              // returns a new object
echo $next->format('Y-m-d');                 // 2024-02-15

$diff = $d->diff($next);                     // DateInterval
echo $diff->days;                            // 31

$ny = $d->setTimezone(new DateTimeZone('America/New_York'));
echo $ny->format('c');                       // ISO 8601 with offset

Core Ideas

What to remember when you work with dates and times in PHP:

IdeaFunction or classRemember
Current timetime() / microtime()time() gives whole seconds; microtime(true) gives a float for timing code
Format a timestampdate() / gmdate()date() uses the default timezone; gmdate() always uses UTC
Parse textstrtotime()Understands 2024-01-15, tomorrow, +2 days; returns false on failure
Build from partsmktime() / checkdate()Argument order is hour, minute, second, month, day, year; validate user dates with checkdate()
Date objectdate_create_immutable()Same as new DateTimeImmutable() but returns false instead of throwing on bad input
Strict inputdate_create_from_format()You state the exact format, such as d/m/Y, so the result is never a guess
Timezonedate_default_timezone_set() / timezone_open()Use names such as Asia/Kolkata, not abbreviations such as IST
Add or subtractdate_add() / date_sub() / date_modify()DateTime changes in place; DateTimeImmutable returns a new object
Differencedate_diff() / date_interval_format()Returns a DateInterval; days holds the total day count

DateTime, DateTimeImmutable, and the procedural names

DateTime is mutable: calling modify() changes the object you already hold, so every variable that points to it sees the change. DateTimeImmutable keeps the original and returns a new object each time. Prefer the immutable class for new code. The procedural functions work on DateTime; for immutable objects use the method form.

Common Format Characters

date() and date_format() use the same characters. Characters not listed as codes, such as - and :, are printed as they are. Escape a letter with a backslash to print it, for example \T. The examples below use 2024-01-15 10:30:00.

CharacterMeaningExample
Y / yFour-digit and two-digit year2024 / 24
m / nMonth with and without leading zero01 / 1
F / MFull and short month nameJanuary / Jan
d / jDay with and without leading zero15 / 15
l / DFull and short weekday nameMonday / Mon
H / h / A24-hour, 12-hour, and AM or PM10 / 10 / AM
i / sMinutes and seconds with leading zero30 / 00
e / T / PTimezone name, abbreviation, and offsetUTC / UTC / +00:00
c / UISO 8601 date and Unix timestamp2024-01-15T10:30:00+00:00 / 1705314600

Deprecated Functions

Some older helpers are deprecated as of PHP 8.1 and raise a deprecation notice when called. They still have guide pages so you can recognize them in old code and replace them:

DeprecatedUse instead
strftime() / gmstrftime()date() or DateTimeImmutable::format() for English output; IntlDateFormatter for localized names
strptime()date_parse_from_format() or DateTimeImmutable::createFromFormat()
date_sunrise() / date_sunset()date_sun_info(), which returns sunrise, sunset, and twilight times in one array
Do not start new code with these.

strftime() also depends on the system locale, which is not the same on every server. Switch to format() or IntlDateFormatter before you upgrade past PHP 8.1.

PHP Examples

Three short scripts that show how dates and times work in PHP. Each one uses a fixed date, so the output is the same every time you run it.

Example 1 — date(), strtotime(), and timestamps

Turn a fixed date string into a Unix timestamp, format it, and move it forward with relative text.

PHP
<?php
date_default_timezone_set('UTC');

$ts = strtotime('2024-01-15 10:30:00');
echo "Timestamp: ", $ts, PHP_EOL;
echo date('l, d F Y H:i', $ts), PHP_EOL;

$nextWeek = strtotime('+1 week', $ts);
echo "Next week: ", date('Y-m-d', $nextWeek), PHP_EOL;

echo "Last day of Feb: ", date('Y-m-d', strtotime('last day of february 2024')), PHP_EOL;
var_dump(checkdate(2, 30, 2024));
?>

How It Works

  1. date_default_timezone_set('UTC') makes the result the same on every server, because date() and strtotime() both use the default timezone.
  2. strtotime() parses the text into seconds since 1970. date() turns that number back into text using the format characters, so l prints the weekday name.
  3. The second argument of strtotime() is the base time for relative text such as +1 week. last day of february 2024 gives 29 because 2024 is a leap year.
  4. checkdate(2, 30, 2024) takes month, day, and year, and returns false because February never has 30 days.

Example 2 — DateTime, DateTimeImmutable, and procedural calls

See how a mutable object changes through every variable, how an immutable one stays the same, and how the procedural functions fit in.

PHP
<?php
date_default_timezone_set('UTC');

$a = new DateTime('2024-01-15');
$b = $a;
$b->modify('+1 day');
echo "DateTime a: ", $a->format('Y-m-d'), PHP_EOL;

$original = new DateTimeImmutable('2024-01-15');
$next     = $original->modify('+1 day');
echo "Immutable original: ", $original->format('Y-m-d'), PHP_EOL;
echo "Immutable new: ", $next->format('Y-m-d'), PHP_EOL;

$d = date_create('2024-01-15');
date_add($d, date_interval_create_from_date_string('10 days'));
echo "Procedural: ", date_format($d, 'Y-m-d'), PHP_EOL;
?>

How It Works

  1. $b = $a copies the handle, not the date, so modify() on $b also moves $a to January 16.
  2. On a DateTimeImmutable, modify() returns a new object. The original still holds January 15, and $next holds January 16.
  3. date_create() builds a DateTime. date_interval_create_from_date_string() turns 10 days into a DateInterval, and date_add() adds it to the same object.
  4. date_format() is the procedural form of $d->format() and uses the same characters.

Example 3 — Timezones, intervals, and diff()

Convert one moment to two other timezones, add a month with DateInterval, and measure the gap between two dates.

PHP
<?php
date_default_timezone_set('UTC');
echo "Default: ", date_default_timezone_get(), PHP_EOL;

$utc   = new DateTimeImmutable('2024-01-15 12:00:00', new DateTimeZone('UTC'));
$ny    = $utc->setTimezone(new DateTimeZone('America/New_York'));
$tokyo = $utc->setTimezone(new DateTimeZone('Asia/Tokyo'));

echo $utc->format('Y-m-d H:i T P'), PHP_EOL;
echo $ny->format('Y-m-d H:i T P'), PHP_EOL;
echo $tokyo->format('Y-m-d H:i T P'), PHP_EOL;

$start = new DateTimeImmutable('2024-01-15');
$end   = new DateTimeImmutable('2024-03-20');

echo "Plus one month: ", $start->add(new DateInterval('P1M'))->format('Y-m-d'), PHP_EOL;

$diff = $start->diff($end);
echo $diff->format('%m months, %d days (%a days total)'), PHP_EOL;
?>

How It Works

  1. date_default_timezone_get() confirms the default set one line earlier. The first object is given an explicit DateTimeZone, so it does not depend on that default.
  2. setTimezone() returns a new object for the same moment. New York is five hours behind UTC in winter and Tokyo is nine hours ahead, so 12:00 UTC is 07:00 and 21:00. T prints the abbreviation and P the offset.
  3. DateInterval('P1M') means a period of one month. add() returns January 15 plus one month, which is February 15.
  4. diff() returns a DateInterval. %m and %d give the calendar parts (2 months, 5 days) and %a gives the total day count (31 + 29 + 5 = 65 in a leap year).

Next: PHP Date/Time Functions Index

After you know timestamps, the two object styles, and timezones, open the functions index for all 51 guides.

Start withWhy
date()Format a timestamp with the format characters
time()Read the current Unix timestamp
strtotime()Turn date text and relative phrases into a timestamp
date_create_immutable()Create a DateTimeImmutable without exceptions
date_default_timezone_set()Set the default timezone for the script
date_diff()Measure the gap between two dates

Full list: PHP Date/Time Functions index (/php/date/function).

Frequently Asked Questions

They are built-in functions and classes for reading the current time, turning text into timestamps, formatting dates for display, converting between timezones, and measuring or adding intervals. The core pieces are date(), time(), strtotime(), the DateTime and DateTimeImmutable classes, DateInterval, and DateTimeZone.
DateTime changes the same object when you call modify(), add(), or setTimezone(). DateTimeImmutable never changes the original: each of those methods returns a new object. Immutable objects are safer because a date passed to another function cannot be changed behind your back.
Use date() with time() or strtotime() for quick formatting of the current time or a Unix timestamp. Use DateTimeImmutable when you need timezones, intervals, comparison, or any date outside the 32-bit timestamp range. Both share the same format characters.
Call date_default_timezone_set('Asia/Kolkata') early in the script, or set date.timezone in php.ini. Read it back with date_default_timezone_get(). For one value only, pass a DateTimeZone object to the DateTime constructor or call setTimezone() instead of changing the default.
Call diff() on one DateTimeImmutable and pass the other. It returns a DateInterval with y, m, d, h, i, and s properties, plus days for the total number of days. Use format('%a days') or read the properties directly.
strtotime() returns false when the text cannot be parsed, for example '2024-13-45'. Always check the result with === false before you pass it to date(). For strict input such as 15/01/2024, DateTimeImmutable::createFromFormat() is safer because you state the exact format.
No. strftime(), gmstrftime(), strptime(), date_sunrise(), and date_sunset() are deprecated as of PHP 8.1 and trigger a deprecation notice. Use date() or DateTime::format() for formatting, IntlDateFormatter for localized output, and date_sun_info() for sunrise and sunset times.

Browse every Date/Time function

Open the functions index for categorized guides with examples and FAQs.

Date/Time Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful