How to format a date using Carbon in PHP?

To format a date using Carbon in PHP, you can follow these steps:

  1. Import the Carbon library by including its namespace at the top of your PHP file:
use Carbon\Carbon;
  1. Create a new instance of Carbon with your desired date:
$date = Carbon::parse('2022-09-15');
  1. Format the date using the format() method. Carbon uses the same formatting directives as the PHP date() function:
$formattedDate = $date->format('Y-m-d');

Here are some common formatting directives:

  • Y: A full numeric representation of a year (4 digits)
  • m: Numeric representation of a month (leading zeros)
  • d: Day of the month (leading zeros)
  • H: 24-hour format of an hour (leading zeros)
  • i: Minutes (leading zeros)
  • s: Seconds (leading zeros)

You can combine these directives with other characters to create custom date formats.

Example:

$date = Carbon::parse('2022-09-15'); $formattedDate = $date->format('Y-m-d H:i:s'); echo $formattedDate;

Output:

2022-09-15 00:00:00

By using Carbon, you can easily manipulate and format dates in PHP.