How to format a DateTime object to display the date and time in a custom format in PHP?

In PHP, you can use the date_format() function to format a DateTime object with a custom format. Here's an example:

$datetime = new DateTime('2022-01-01 12:34:56'); $formatted = date_format($datetime, 'Y-m-d H:i:s'); echo $formatted; // Output: 2022-01-01 12:34:56

In the above example, we create a new DateTime object with a specific date and time. Then, we use the date_format() function to format it according to a custom format. In this case, the format 'Y-m-d H:i:s' represents the year, month, day, hour, minute, and second.

You can customize the format as per your requirements using the available formatting options in PHP. Here are some commonly used formatting options:

  • Y: The year with 4 digits (e.g., 2022)
  • m: The month with leading zeros (e.g., 01)
  • d: The day with leading zeros (e.g., 01)
  • H: The hour in 24-hour format with leading zeros (e.g., 12)
  • i: The minute with leading zeros (e.g., 34)
  • s: The second with leading zeros (e.g., 56)

You can combine these formatting options with any desired separators in between.