nesbot/carbon
Carbon is a PHP DateTime extension that makes working with dates and times simple and readable. Parse, format, compare, add/subtract intervals, handle timezones and localization, and use fluent, human-friendly helpers for common date tasks.
Installation & Setup: Carbon is pre-installed in Laravel (v9+). Verify with:
composer show nesbot/carbon
For newer features, update via:
composer require nesbot/carbon:^3.0
Alias Carbon globally in config/app.php:
'aliases' => [
'Carbon' => Illuminate\Support\Facades\Carbon::class,
],
First Use Case:
Replace DateTime in your first model/controller:
use Carbon\Carbon;
// Current time (timezone-aware)
$now = Carbon::now('America/Chicago');
// Parse from string (flexible formats)
$event = Carbon::parse('2024-12-25T18:00:00+00:00');
// Format for display
echo $event->format('Y-m-d H:i'); // "2024-12-25 18:00"
Where to Look First:
now(), today(), yesterday() (all return Carbon instances).parse(), addX(), subX(), diff(), and format().app/Providers/AppServiceProvider.php for custom Carbon methods.Carbon::setTestNow() to freeze time in tests:
Carbon::setTestNow(Carbon::parse('2024-01-01'));
Replace all new DateTime() with Carbon for fluent syntax and timezone support:
// Vanilla PHP
$date = new DateTime('2024-01-01', new DateTimeZone('UTC'));
// Carbon (recommended)
$date = Carbon::create(2024, 1, 1, 0, 0, 0, 'UTC');
// OR
$date = Carbon::parse('2024-01-01 00:00:00 UTC');
$nextWeek = now()->copy()->addWeek()->startOfDay();
$date->addDays(5)->hour(9)->minute(0);
$deadline = now()->copy()->addBusinessDays(3)->hour(17);
$start = now()->startOfDay();
$end = now()->endOfDay();
app.locale):
Carbon::setLocale(app()->getLocale());
echo now()->translatedFormat('l, F jS Y'); // "Wednesday, December 25th 2024"
echo now()->diffForHumans($event); // "in 3 hours"
echo now()->diffForHumans($event, true); // "in 3 hours from now"
$date->format('Y-m-d H:i:s') // ISO 8601
$date->format('d/m/Y') // DD/MM/YYYY
$userTime = now()->timezone($user->timezone);
if (now('Europe/London')->isSameDay(now('America/New_York'))) {
// Logic for overlapping days
}
$date->setTimezone('UTC')->toDateTimeString();
// Accessor: Convert DB timestamp to Carbon
public function getCreatedAtAttribute($value) {
return Carbon::parse($value)->setTimezone('UTC');
}
// Mutator: Store Carbon as timestamp
public function setDueDateAttribute($value) {
$this->attributes['due_date'] = Carbon::parse($value)->timestamp;
}
public function scopeThisMonth($query) {
return $query->whereBetween('created_at', [
now()->startOfMonth(),
now()->endOfMonth()
]);
}
Carbon::setTestNow(Carbon::parse('2024-01-15 10:00:00'));
assert helpers):
$this->assertTrue(now()->isToday());
$this->assertEquals('2024-01-15', now()->format('Y-m-d'));
Carbon::setTestNow(Carbon::parse('2024-12-31'));
Extend Carbon in AppServiceProvider:
Carbon::macro('isBusinessDay', function () {
$day = $this->dayOfWeek;
return !in_array($day, [Carbon::SATURDAY, Carbon::SUNDAY]);
});
Carbon::macro('nextBusinessDay', function () {
return $this->copy()->addDay()->isBusinessDay() ? $this : $this->nextBusinessDay();
});
Usage:
if (now()->isBusinessDay()) {
// Process business logic
}
$nextDay = now()->nextBusinessDay();
Timezone Confusion:
// ❌ Avoid: Ambiguous timezone
$date = Carbon::now(); // Uses system timezone
// ✅ Prefer: Explicit timezone
$date = Carbon::now('UTC');
Immutable vs. Mutable:
// ❌ Unintended mutation
$date = now()->addDay();
$date->subDay(); // Affects the same instance
copy() for immutable operations:
$date = now()->copy()->addDay();
Locale Fallbacks:
// ❌ May fail if 'fr' locale is missing
Carbon::setLocale('fr');
echo now()->translatedFormat('l');
Carbon::setLocale('fr', 'en'); // Fallback to English
Daylight Saving Time (DST):
// ❌ Edge case: DST transition at 2 AM
$date = Carbon::parse('2024-03-10 02:30:00 America/New_York');
Serialization Issues:
// ❌ May fail in queues
$job = new ProcessOrder($order->created_at);
$job = new ProcessOrder($order->created_at->timestamp);
// OR
$job = new ProcessOrder($order->created_at->toIso8601String());
now()->addDays(365)->subHours(12)->format('...')).How can I help you explore Laravel packages today?