How to extract and display the day, month, and year from a date using Carbon in PHP?

To extract and display the day, month, and year from a date using Carbon in PHP, you can use the following steps:

  1. Install Carbon using composer by running the following command in your project directory:
composer require nesbot/carbon
  1. Import the Carbon class using the use statement:
use Carbon\Carbon;
  1. Create a new Carbon object by parsing the date string:
$date = Carbon::parse("2022-12-31");
  1. Use the day, month, and year methods to get the respective values:
$day = $date->day; $month = $date->month; $year = $date->year;
  1. Display the extracted values:
echo "Day: $day\n"; echo "Month: $month\n"; echo "Year: $year\n";

Here's the complete example:

use Carbon\Carbon; $date = Carbon::parse("2022-12-31"); $day = $date->day; $month = $date->month; $year = $date->year; echo "Day: $day\n"; // Output: Day: 31 echo "Month: $month\n"; // Output: Month: 12 echo "Year: $year\n"; // Output: Year: 2022

Make sure you have Carbon installed and imported correctly, and replace "2022-12-31" with your desired date string.