What is Carbon?
Carbon is a popular library for working with dates and time in PHP. It is an extension of the built-in DateTime class and provides a more convenient, readable, and functional API. Carbon is often called "DateTime for humans" because it simplifies date manipulation, formatting, calculating differences, and working with time zones.
Why is Carbon needed?
Built-in PHP functions for working with dates (date(), strtotime(), DateTime) often require cumbersome code and are hard to read. Carbon solves these problems:
- Intuitive methods:
->addDays(),->subMonths(),->diffForHumans(). - Localization and output of "human" formats (e.g., "2 days ago").
- Simple work with time zones.
- Immutable objects for safe operations.
Installation
Install Carbon via Composer:
composer require nesbot/carbonAfter installation, include the library:
<?php
require 'vendor/autoload.php';
use Carbon\\Carbon;Main functions with examples
1. Creating a date
// Current date and time
$now = Carbon::now();
// From a string
$date = Carbon::parse('2025-03-15');
// From a format
$date = Carbon::createFromFormat('Y-m-d', '2025-03-15');2. Date manipulation
$date = Carbon::now();
// Add 7 days
$date->addDays(7);
// Subtract 1 month
$date->subMonth();
// Start of month
$date->startOfMonth();3. Difference between dates
$start = Carbon::parse('2025-01-01');
$end = Carbon::parse('2025-12-31');
// Number of days
$days = $start->diffInDays($end); // 364
// Human-readable format
echo $start->diffForHumans($end); // "11 months after"4. Formatting
$date = Carbon::now();
echo $date->toDateString(); // 2025-03-15
echo $date->format('l jS \\of F Y'); // Saturday 15th of March 20255. Date checking
$date = Carbon::parse('2025-03-15');
var_dump($date->isWeekend()); // true (Saturday)
var_dump($date->isFuture()); // false
var_dump($date->isPast()); // trueWhen to use Carbon?
Carbon is ideal for:
- Web applications where you need to display relative dates ("just now", "2 hours ago").
- Booking systems, calendars, task schedulers.
- APIs that require flexible date formatting for different time zones.
- Any project where date code needs to be readable and maintainable.
If you use Laravel or Symfony frameworks, Carbon is already built into them by default.
Conclusion
Carbon is a must-have library for any PHP developer. It saves time, makes code cleaner, and eliminates common errors when working with dates. Install it in your project today!