Formatting dates with date()
Learn to print dates with the date() function and format characters.
The date() function
In PHP you use the date() function to print dates and times. The function takes a format string and an optional timestamp and returns a formatted date string.
For example, date('Y-m-d') prints today's date like 2024-06-15. The letters in the format string stand for date parts: Y gives a four-digit year, m a zero-padded month, d a zero-padded day.
PHP uses the server timezone by default; call date_default_timezone_set('UTC') for consistent results.
Common format characters
The most used letters in a format string are: Y four-digit year (2024), y two-digit year (24), m zero-padded month (01–12), n month without leading zero, d zero-padded day (01–31), j day without leading zero.
For time: H 24-hour zero-padded hour (00–23), i zero-padded minute, s zero-padded second. For example, date('H:i:s') may output 14:30:05.
You combine these letters to build any format; separators (. : / -) are written as-is.
Exercise Format a fixed timestamp
Format the given $ts = 1700000000 timestamp with date() using the 'd.m.Y' format and print it with echo.
Show example solution
Print date('d.m.Y', $ts) with echo.
Example solution:
<?php
date_default_timezone_set('UTC');
$ts = 1700000000;
echo date('d.m.Y', $ts);
Test yourself
-
What does date('Y') return?
- Month name (e.g. January)
- Four-digit year (e.g. 2024)
- Month number (e.g. 1)
- Hour (e.g. 14)
Show answer
Four-digit year (e.g. 2024) — Correct. The 'Y' format character returns the four-digit year.
-
Format the date as day.month.year
$formatted = date('____', $ts);Show answer
$formatted = date('d.m.Y', $ts); -
Match format characters
- Y
- Four-digit year
- m
- Zero-padded month (01-12)
- d
- Zero-padded day (01-31)
- H
- Zero-padded hour (00-23)