PHP Date and Time

PHP's built-in date() function lets you format the current date and time (or any timestamp) into readable strings using a set of format characters.

Working with dates in PHP

Almost every application needs to show dates: a blog post's publish time, an order's creation date, or a simple 'last updated' label. PHP stores a moment in time as a Unix timestamp, which is the number of seconds since midnight (UTC) on January 1, 1970. The date() function turns that raw number into a formatted string you can display to users.

The function takes two arguments. The first is a format string made of special characters that each stand for a piece of the date. The second is an optional timestamp; when you leave it out, PHP uses the current time returned by time().

Formatting the current date

<?php
// Full date like: Wednesday, 15 July 2026
echo date("l, j F Y");

// A common numeric format: 2026-07-15
echo date("Y-m-d");

// Date and time together: 2026-07-15 14:30:05
echo date("Y-m-d H:i:s");
?>

Common format characters

The format string is case sensitive, so 'm' and 'M' produce very different output. The table below lists the characters you will reach for most often when building date and time strings.

CharacterMeaningExample output
dDay of the month, two digits01 to 31
jDay of the month, no leading zero1 to 31
DShort weekday nameMon
lFull weekday nameMonday
mMonth number, two digits01 to 12
nMonth number, no leading zero1 to 12
MShort month nameJul
FFull month nameJuly
YFour-digit year2026
yTwo-digit year26
HHour, 24-hour format00 to 23
hHour, 12-hour format01 to 12
iMinutes, two digits00 to 59
sSeconds, two digits00 to 59
AUppercase AM or PMPM
Note: The date() function always works in the server's default time zone. Set it explicitly at the top of your script with date_default_timezone_set("Asia/Kolkata") so your dates are predictable no matter where the code runs.

Building a specific date with mktime()

When you need a date other than 'now', mktime() creates a timestamp from individual parts. Its arguments are hour, minute, second, month, day, and year, in that order. You can then pass that timestamp as the second argument to date().

Creating and formatting a custom date

<?php
// Build a timestamp for 15 August 2026, 09:00:00
$timestamp = mktime(9, 0, 0, 8, 15, 2026);

echo date("l, j F Y", $timestamp);
// Output: Saturday, 15 August 2026

// strtotime() reads plain-English dates
$next = strtotime("next Monday");
echo date("Y-m-d", $next);
?>
  • Use time() to get the current Unix timestamp as an integer.
  • Use strtotime() to convert readable text like '+1 week' or '2026-12-25' into a timestamp.
  • For heavier date math (differences, adding intervals), the object-oriented DateTime class is more flexible than date().
  • Escape any literal letter in a format string with a backslash so PHP does not treat it as a format character.

Exercise: PHP Date and Time

What does PHP's built-in time() function return?