How to convert a timestamp to a readable date and time format using Carbon in PHP?

To convert a timestamp to a readable date and time format using Carbon in PHP, you can follow these steps:

  1. Install Carbon package using Composer by running the following command in your project directory:
composer require nesbot/carbon
  1. Use the Carbon namespace in your PHP file:
use Carbon\Carbon;
  1. Create a new Carbon instance using the timestamp:
$timestamp = 1597294800; // Replace with your timestamp $carbon = Carbon::createFromTimestamp($timestamp);
  1. Format the Carbon instance to the desired readable date and time format using the format() method:
$formattedDateTime = $carbon->format('Y-m-d H:i:s');

The format parameter ('Y-m-d H:i:s') can be modified according to your requirements. Here are some common format options:

  • 'Y-m-d': Year-month-day (e.g., 2021-09-20)
  • 'Y-m-d H:i:s': Year-month-day hour:minute:seconds (e.g., 2021-09-20 15:30:45)
  • 'M j, Y H:i:s': Month day, Year hour:minute:seconds (e.g., Sep 20, 2021 15:30:45)
  • 'D, M j, Y': Weekday, Month day, Year (e.g., Mon, Sep 20, 2021)

That's it! Now $formattedDateTime will contain the timestamp converted to the desired readable format.