0
0
PhpHow-ToBeginner · 3 min read

How to Format Date in PHP: Simple Guide with Examples

In PHP, you format dates using the date() function by passing a format string that defines how the date should appear. For example, date('Y-m-d') outputs the date as year-month-day like 2024-06-01.
📐

Syntax

The date() function formats a local date and time, returning it as a string. It takes two parameters:

  • format (string): Specifies the output format using characters like Y for full year, m for month, d for day, etc.
  • timestamp (optional integer): A Unix timestamp to format. If omitted, the current date and time is used.
php
string date(string $format, int|null $timestamp = null)
💻

Example

This example shows how to format the current date as year-month-day and a custom timestamp as a readable date and time.

php
<?php
// Format current date as YYYY-MM-DD
echo date('Y-m-d') . "\n";

// Format a specific timestamp (e.g., 1st Jan 2020 15:30:00)
$timestamp = mktime(15, 30, 0, 1, 1, 2020);
echo date('l, F j, Y H:i:s', $timestamp);
?>
Output
2024-06-01 Wednesday, January 1, 2020 15:30:00
⚠️

Common Pitfalls

Common mistakes include:

  • Using incorrect format characters (e.g., MM instead of m for month).
  • Not providing a timestamp when formatting a specific date, which defaults to the current date.
  • Confusing date() with strtotime() which parses strings into timestamps.
php
<?php
// Wrong: 'MM' is not a valid format for month
// echo date('YYYY-MM-DD'); // Incorrect

// Right:
echo date('Y-m-d'); // Correct
?>
Output
2024-06-01
📊

Quick Reference

Format CharacterMeaningExample Output
Y4-digit year2024
y2-digit year24
m2-digit month (01-12)06
nMonth without leading zero (1-12)6
d2-digit day (01-31)01
jDay without leading zero (1-31)1
H24-hour format (00-23)15
h12-hour format (01-12)03
iMinutes with leading zero (00-59)30
sSeconds with leading zero (00-59)00
lFull weekday nameWednesday
FFull month nameJanuary

Key Takeaways

Use the date() function with a format string to display dates in PHP.
Remember to use correct format characters like Y for year, m for month, and d for day.
If no timestamp is given, date() returns the current date and time.
Avoid common mistakes like using uppercase MM for month; use lowercase m instead.
Use mktime() or strtotime() to create timestamps for formatting specific dates.