0
0
PhpHow-ToBeginner · 3 min read

How to Get Current Date in PHP: Simple Guide

Use the date() function in PHP to get the current date. For example, date('Y-m-d') returns the date in year-month-day format like 2024-06-01.
📐

Syntax

The date() function formats the current date and time according to the string you provide. The string uses format characters like Y for a 4-digit year, m for month, and d for day.

Example format: date('Y-m-d') returns the date as year-month-day.

php
date(string $format): string
💻

Example

This example shows how to get and print the current date in the format YYYY-MM-DD.

php
<?php
// Get current date in year-month-day format
$currentDate = date('Y-m-d');
echo "Today's date is: $currentDate";
?>
Output
Today's date is: 2024-06-01
⚠️

Common Pitfalls

  • Not setting the correct timezone can cause the date to be off. Use date_default_timezone_set() to set your timezone.
  • Using wrong format characters will give unexpected results. For example, m is month, M is short month name.
  • Calling date() without parentheses or quotes around the format string causes errors.
php
<?php
// Wrong: missing quotes around format string
// echo date(Y-m-d); // Causes error

// Correct: quotes around format string
echo date('Y-m-d');

// Set timezone to avoid wrong date
// date_default_timezone_set('America/New_York');
📊

Quick Reference

Format CharacterMeaningExample
Y4-digit year2024
y2-digit year24
mMonth with leading zero06
nMonth without leading zero6
dDay with leading zero01
jDay without leading zero1

Key Takeaways

Use the date() function with a format string to get the current date in PHP.
Always set the timezone with date_default_timezone_set() to get accurate dates.
Use correct format characters like 'Y' for year, 'm' for month, and 'd' for day.
Put the format string inside quotes when calling date(), like date('Y-m-d').