Current Location: Home> Latest Articles> PHP Date Formatting Tutorial: Easily Convert to Year-Month-Day

PHP Date Formatting Tutorial: Easily Convert to Year-Month-Day

M66 2025-10-27

Convert Dates to Year-Month-Day in PHP

In PHP development, handling dates is a common requirement. The date_format() function allows you to easily format dates into the 'year-month-day' format.

Introduction to date_format() Function

The date_format() function accepts two parameters: a datetime string and a format string. The format characters for year, month, and day are as follows:

  • Y: Year (4 digits)
  • m: Month (2 digits, with leading zero)
  • d: Day (2 digits, with leading zero)

Example Code

$date = '2023-05-18';

// Convert the date to year-month-day format
$formattedDate = date('Y-m-d', strtotime($date));

echo $formattedDate; // Output: 2023-05-18

Notes

  • If the input datetime string is invalid, date_format() will return FALSE.
  • If the format string contains undefined format characters, the function will also return FALSE.
  • The order of format characters must match the order of date components in the input string; otherwise, the function will return FALSE.

Using this method, you can easily format any valid date string into a standard year-month-day format, which is useful for consistent date management and display in PHP projects.