0
0
PhpHow-ToBeginner · 3 min read

How to Use Date Function in PHP: Syntax and Examples

In PHP, use the date() function to format the current date and time or a timestamp. You provide a format string to specify how the date should appear, like date('Y-m-d') for year-month-day format.
📐

Syntax

The date() function formats a date or time according to the format string you provide. It takes two parameters:

  • format (required): A string that defines how the date/time should be formatted using special characters.
  • timestamp (optional): An integer Unix timestamp to format. If omitted, the current date/time is used.

Example format characters include Y for a 4-digit year, m for month, and d for day.

php
string date(string $format, int $timestamp = null)
💻

Example

This example shows how to get the current date in Year-Month-Day format and how to format a specific timestamp.

php
<?php
// Current date in Y-m-d format
echo date('Y-m-d') . "\n";

// Format a specific timestamp (e.g., 1 Jan 2020)
echo date('l, F j, Y', 1577836800) . "\n";
?>
Output
2024-06-14 Wednesday, January 1, 2020
⚠️

Common Pitfalls

Common mistakes when using date() include:

  • Forgetting that the format string is case-sensitive, so m means month, but M means short month name.
  • Not providing a timestamp when you want to format a date other than the current time.
  • Using incorrect format characters that produce unexpected results.

Always check the PHP manual for correct format characters.

php
<?php
// Wrong: Using uppercase M for month number
// echo date('Y-M-d'); // Outputs year, short month name, day

// Right: Use lowercase m for month number
// echo date('Y-m-d');
?>
📊

Quick Reference

Format CharacterMeaningExample Output
Y4-digit year2024
y2-digit year24
m2-digit month06
nMonth without leading zero6
d2-digit day14
jDay without leading zero14
H24-hour format15
h12-hour format03
iMinutes with leading zeros07
sSeconds with leading zeros09
lFull weekday nameFriday
DShort weekday nameFri

Key Takeaways

Use the date() function with a format string to display dates in PHP.
The format string is case-sensitive and controls how the date appears.
If no timestamp is given, date() uses the current date and time.
Check PHP documentation for correct format characters to avoid errors.
Use timestamps to format dates other than the current moment.