PHP Logonesbot/carbon

"nesbot/carbon" is a popular, open-source PHP library that extends the native `DateTime` class, providing a more intuitive, fluent, and robust API for handling dates and times. It aims to simplify common date and time operations, making code more readable and easier to maintain. Carbon is widely used in the PHP ecosystem, including frameworks like Laravel, due to its comprehensive feature set and user-friendly interface.

Key features and benefits of using Carbon include:

* Fluent Interface: Carbon offers a method chaining approach, allowing multiple operations to be performed on a date/time object in a single, readable line of code.
* Easy Instantiation: Creating `Carbon` instances is straightforward, supporting various input formats like timestamps, strings, or parts of a date.
* Manipulation and Arithmetic: It provides simple methods for adding or subtracting years, months, days, hours, minutes, and seconds, as well as specific methods like `startOfDay()`, `endOfMonth()`, etc.
* Formatting: Carbon simplifies date and time formatting with pre-defined constants and custom format strings, making it easy to display dates in various human-readable formats.
* Difference Calculations: Calculating differences between two `Carbon` instances is intuitive, with methods like `diffInDays()`, `diffInMonths()`, and especially `diffForHumans()` for human-friendly output (e.g., "3 days ago", "in 5 minutes").
* Timezone Support: Comprehensive support for timezones, allowing easy conversion between different timezones.
* Internationalization (Locales): Carbon supports various locales, enabling the output of dates and times in different languages, which is crucial for global applications.
* Immutability/Mutability: Carbon allows you to choose between mutable (changes the current object) and immutable (returns a new object) date instances, promoting safer date manipulation. By default, `Carbon` objects are mutable, but `CarbonImmutable` provides immutability.
* Macros: It's macroable, meaning you can extend its functionality by adding custom methods.
* Comparison: Simple methods for comparing dates (e.g., `isSameDay()`, `isBefore()`, `isAfter()`).

Carbon significantly reduces the boilerplate code often associated with PHP's native `DateTime` functions, making date and time management in PHP applications much more efficient and less error-prone.

Example Code

<?php

require 'vendor/autoload.php';

use Carbon\\Carbon;
use Carbon\\CarbonImmutable;

// --- 1. Creating Carbon Instances ---

// Current date and time
$now = Carbon::now();
echo "Current time: " . $now->toDateTimeString() . "\n";

// From a specific date and time string
$specificDate = Carbon::parse('2023-10-27 15:30:00');
echo "Specific date: " . $specificDate->toDayDateTimeString() . "\n";

// From parts
$dateFromParts = Carbon::create(2024, 1, 15, 10, 0, 0);
echo "Date from parts: " . $dateFromParts->format('l, F jS, Y h:i A') . "\n";

// Using CarbonImmutable for immutable instances
$immutableNow = CarbonImmutable::now();
echo "Immutable current time: " . $immutableNow->toDateTimeString() . "\n";

// --- 2. Formatting Dates ---

echo "\n--- Formatting ---\n";
echo "Default format: " . $now . "\n"; // __toString() uses default
echo "Formatted (human readable): " . $now->format('F j, Y, g:i A') . "\n";
echo "Short date: " . $now->toDateString() . "\n";
echo "Time only: " . $now->toTimeString() . "\n";
echo "Difference for humans: " . $specificDate->diffForHumans($now) . "\n"; // '1 week ago' or 'in 1 week'

// --- 3. Date and Time Manipulation ---

echo "\n--- Manipulation ---\n";

// Add 1 day
$tomorrow = $now->copy()->addDay(); // Use copy() for mutable objects if you don't want to modify $now
echo "Tomorrow: " . $tomorrow->toDateTimeString() . "\n";

// Subtract 3 hours
$threeHoursAgo = $now->copy()->subHours(3);
echo "3 hours ago: " . $threeHoursAgo->toTimeString() . "\n";

// Go to the start of the month
$startOfMonth = $now->copy()->startOfMonth();
echo "Start of month: " . $startOfMonth->toDateTimeString() . "\n";

// Using an immutable instance for manipulation (returns a new instance)
$nextYearImmutable = $immutableNow->addYear();
echo "Immutable original: " . $immutableNow->toDateTimeString() . "\n";
echo "Immutable next year: " . $nextYearImmutable->toDateTimeString() . "\n";


// --- 4. Timezones ---

echo "\n--- Timezones ---\n";
$utcTime = Carbon::now('UTC');
echo "UTC Time: " . $utcTime->toDateTimeString() . "\n";

$londonTime = $utcTime->setTimezone('Europe/London');
echo "London Time: " . $londonTime->toDateTimeString() . "\n";

$nyTime = $utcTime->setTimezone('America/New_York');
echo "New York Time: " . $nyTime->toDateTimeString() . "\n";


// --- 5. Internationalization (Locales) ---

echo "\n--- Locales ---\n";
// Set a global locale (for subsequent Carbon instances)
Carbon::setLocale('fr');
$frenchDate = Carbon::now();
echo "French date (global): " . $frenchDate->isoFormat('dddd Do MMMM YYYY') . "\n"; // e.g., "vendredi 27 octobre 2023"

// Or set locale for a specific instance
$germanDate = Carbon::now()->locale('de');
echo "German date (instance): " . $germanDate->isoFormat('dddd, DD. MMMM YYYY') . "\n"; // e.g., "Freitag, 27. Oktober 2023"

// Reset to default (or 'en')
Carbon::setLocale('en');
$englishDate = Carbon::now();
echo "English date (reset): " . $englishDate->isoFormat('dddd, MMMM Do YYYY') . "\n";


// --- 6. Comparisons ---

echo "\n--- Comparisons ---\n";
$date1 = Carbon::parse('2023-10-27 10:00:00');
$date2 = Carbon::parse('2023-10-27 12:00:00');
$date3 = Carbon::parse('2023-10-28 10:00:00');

echo "Is date1 same day as date2? " . ($date1->isSameDay($date2) ? 'Yes' : 'No') . "\n"; // Yes
echo "Is date1 before date2? " . ($date1->isBefore($date2) ? 'Yes' : 'No') . "\n";   // Yes
echo "Is date2 after date3? " . ($date2->isAfter($date3) ? 'Yes' : 'No') . "\n";     // No

// You would typically install Carbon via Composer:
// composer require nesbot/carbon