PHP Dates

Format the current date and time with the date() function.

Syntaxdate("Y-m-d");

The date() function formats a timestamp into a readable string. You pass it a format string made of special characters:

CharMeaning
Y4-digit year
mMonth (01-12)
dDay (01-31)
H:i:sHours:minutes:seconds
lFull weekday name

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Format today's date as 'YYYY-MM-DD' with date() when inserting a record's created_at value.
  • Display a human-friendly date like 'Wednesday, 16 July 2026' on a blog post header.
  • Calculate the day of the week with date('l') to show weekend-only promotions automatically.

More examples

Basic date() formatting

date() formats the current timestamp using format characters; Y=4-digit year, m=month, d=day, H=24h hour.

Example · php
<?php
echo date('Y-m-d');          // 2026-07-16
echo date('d/m/Y');          // 16/07/2026
echo date('l, d F Y');       // Thursday, 16 July 2026
echo date('H:i:s');          // current time e.g. 14:30:00

Formatting a specific timestamp

mktime() builds a Unix timestamp from individual date parts; date() formats it using the same format string.

Example · php
<?php
$timestamp = mktime(9, 0, 0, 12, 25, 2026); // 25 Dec 2026 09:00

echo date('l, d F Y \a\t H:i', $timestamp);
// Friday, 25 December 2026 at 09:00

strtotime for relative dates

strtotime() parses English date phrases into a Unix timestamp, making relative date arithmetic straightforward.

Example · php
<?php
$expiry    = strtotime('+30 days');
$lastMonth = strtotime('first day of last month');

echo date('Y-m-d', $expiry);    // 30 days from today
echo date('Y-m-d', $lastMonth); // first day of last month

Discussion

  • Be the first to comment on this lesson.