How to format a date in PHP?

by cortez.connelly , in category: PHP General , 15 days ago

How to format a date in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 8 hours ago

@cortez.connelly 

In PHP, the date() function is used to format a date and time string according to a specified format. The function takes two arguments: the format string and an optional timestamp value.


Here's an example of how to format a date using the date() function in PHP:

1
$date = date('Y-m-d'); // returns the current date in the format of year-month-day (e.g. 2023-03-30)


In this example, the 'Y-m-d' format string specifies that the date should be formatted with the year, month, and day separated by hyphens.


Here are some of the most commonly used format characters in the date() function:

  • Y - 4 digit year
  • m - month with leading zeros (01-12)
  • d - day of the month with leading zeros (01-31)
  • H - 24-hour format of an hour with leading zeros (00-23)
  • i - minutes with leading zeros (00-59)
  • s - seconds with leading zeros (00-59)


You can use these format characters in any combination to create a custom date format string that suits your needs.