Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How Do You Work with Dates and Times in PHP?

PHP
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedDec 5, 2026
7 min read

To work with dates and times in PHP, use the DateTimeImmutable class for anything beyond a quick timestamp, and use date() and time() for simple formatting of the current moment. The php date time toolkit covers four jobs: getting the current time, formatting it, parsing text into a date, and doing arithmetic such as "add 30 days". This guide shows the procedural functions first, then the object API you should prefer in modern PHP 8.x code.

Dates look simple until you meet month ends, leap years and daylight saving. Letting PHP's built-in classes do that work is always safer than adding seconds by hand.

Table of Contents

  • Getting the current time with time() and date()
  • Common date format characters
  • Using DateTimeImmutable for modern code
  • Parsing text into dates
  • Date arithmetic with add, sub and DateInterval
  • Comparing dates and finding the difference
  • Frequently Asked Questions
    • What is the difference between DateTime and DateTimeImmutable?
    • Why does date() show the wrong time?
    • How do I get the current year or month only?
    • Should I store dates as timestamps or strings?
  • Summary
  • Related Articles

Getting the current time with time() and date()

time() returns the current Unix timestamp: the number of seconds since 1 January 1970 00:00:00 UTC. A timestamp is just an integer, so it is easy to store and compare.

date() turns a timestamp into a formatted string using the server's default time zone. Without a second argument it formats the current time.

php
text

The exact numbers depend on when you run it. The format characters are letters, and any letter PHP does not recognise is printed as is, so escape literal text with a backslash.

Common date format characters

The same format characters are used by date(), DateTime::format() and DateTimeImmutable::format().

CharacterMeaningExample
YFour digit year2026
yTwo digit year26
mMonth with leading zero03
nMonth without leading zero3
F / MFull / short month nameNovember / Nov
dDay of month with leading zero07
jDay of month without leading zero7
l / DFull / short weekday nameTuesday / Tue
H / hHour 24-hour / 12-hour14 / 02
iMinutes05
sSeconds09
AAM or PMPM
T / eTime zone abbreviation / identifierCET / Europe/Paris
cISO 8601 date2026-11-17T09:30:00+00:00

For machine-to-machine data, prefer ISO 8601 (c or the constant DateTimeInterface::ATOM) because every language can parse it.

Using DateTimeImmutable for modern code

DateTimeImmutable is an object that holds one moment in time. Every change returns a new object and leaves the original untouched, which prevents the classic bug where a helper function silently modifies a date you still need. The older DateTime class has the same methods but mutates itself.

php
text

The output surprises many people: 31 January plus one month is "31 February", which does not exist, so PHP rolls over into March. If you want the last day of the next month, ask for it explicitly with $start->modify('last day of next month').

new DateTimeImmutable() with no argument means "now". Passing a string such as 'tomorrow noon' or 'next monday' also works because the constructor understands PHP's relative date formats.

Parsing text into dates

There are two parsers, and the difference matters.

  • strtotime() guesses the format and returns a timestamp, or false on failure.
  • DateTimeImmutable::createFromFormat() demands an exact format and returns false when the text does not match.
php

Always prefer createFromFormat() for user input. A string like 03/04/2026 means 3 April in most of the world and 4 March in the United States, and strtotime() picks one silently. Since PHP 8.2, getLastErrors() returns false when there were no warnings or errors, so check for false first, as above. A value such as 31/02/2026 is parsed but produces a warning, because PHP rolls it forward to March.

Date arithmetic with add, sub and DateInterval

A DateInterval describes a span such as "3 days" or "1 year and 2 hours". You build it from an ISO 8601 duration string: P starts a period, T separates date parts from time parts.

php
text

Prefer add() and sub() over adding 86400 * $days seconds to a timestamp. A day is not always 86,400 seconds in a time zone that changes its clocks.

Comparing dates and finding the difference

You can compare two date objects with <, > and ==. To measure the gap, use diff(), which returns a DateInterval.

php
text

The days property is the total number of days between the dates, while d in format() is only the leftover days after whole months are counted. Use days when you need a plain day count.

Walking through a range is easy with DatePeriod:

php

Frequently Asked Questions

What is the difference between DateTime and DateTimeImmutable?

DateTime changes itself when you call modify(), add() or setDate(), while DateTimeImmutable returns a new object each time. Immutable objects are safer to pass around, so use them by default.

Why does date() show the wrong time?

date() uses the default time zone, which comes from the date.timezone setting or date_default_timezone_set(). If your server is in UTC and your users are not, the output looks off. A related article covers time zones in depth.

How do I get the current year or month only?

Use date('Y') and date('n'), or (new DateTimeImmutable())->format('Y'). Calling format() repeatedly on one object avoids a rare mismatch if the clock ticks over midnight between calls.

Should I store dates as timestamps or strings?

Store timestamps or ISO 8601 strings in UTC, and format them only when you display them. Both sort correctly and avoid ambiguity.

Summary

Use time() and date() for quick jobs, and DateTimeImmutable for real work. Parse user input with createFromFormat() and check for false. Do arithmetic with add(), sub(), modify() and DateInterval, never by multiplying seconds, and measure gaps with diff(). Next you will see how time zones change what these objects mean.

Related Articles

  • How Do Regular Expressions Work in PHP (preg functions)?
  • How Do You Use the DateTime Class and Time Zones in PHP?
  • Learn PHP: Complete Study Roadmap from Beginner to Advanced
Share