Carbon PHP Extension
repository·master·Indexed 12 days ago
https://github.com/briannesbitt/carbonAn international PHP extension for the native DateTime class that provides a fluent API for date and time manipulation, localization, and comparison. It includes features for human-readable differences via diffForHumans(), timezone management with CarbonTimeZone, immutable periods via CarbonPeriodImmutable, and time mocking for testing using setTestNow().
What's inside Carbon
- Carbon is available as part of the Tidelift Subscription. This provides commercial support and maintenance for the package, aimed at reducing risk and improving code health for enterprise users. Support is delivered by the package maintainers through the Tidelift platform.
Install Carbon via Composer
masterThe recommended way to install Carbon is using Composer. Run the following command in your terminal:
$ composer require nesbot/carbonAlternatively, you can manually add it to your
composer.jsonfile:{ "require": { "nesbot/carbon": "^3" } }After installation, ensure you require the Composer autoloader in your PHP script to use Carbon classes.
Install Carbon without Composer
masterIf you are not using Composer, download the latest release ZIP archive from the GitHub releases page. Extract the contents into a directory within your project, then require the
autoload.phpfile located in that directory to load Carbon and its dependencies.<?php require 'path-to-Carbon-directory/autoload.php'; use Carbon// Carbon class printf("Now: %s", Carbon::now());<?php require 'path-to-Carbon-directory/autoload.php'; use Carbon\Carbon; printf("Now: %s", Carbon::now());Basic usage of Carbon
masterCarbon extends PHP's
DateTimeclass to provide an easier, more expressive API for date and time manipulation. You can create instances usingnow(),parse(),create(), orcreateFromDate(). Common operations include adding/subtracting time (addDay(),subWeek()), formatting (toDateTimeString(),isoFormat()), and calculating differences (diffInDays(),diffForHumans()).Carbon supports internationalization via the
locale()method and provides human-readable differences.<?php use Carbon\Carbon; // Get current time printf("Right now is %s", Carbon::now()->toDateTimeString()); // Timezones printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // Manipulation $tomorrow = Carbon::now()->addDay(); $lastWeek = Carbon::now()->subWeek(); // Creation $howOldAmI = Carbon::createFromDate(1975, 5, 21)->age; $noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London'); // Localization and Human-readable differences echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago' echo Carbon::now()->subMinutes(2)->locale('zh_CN')->diffForHumans(); // '2分钟前' echo Carbon::parse('2019-07-23 14:51')->locale('fr_FR')->isoFormat('LLLL'); // 'mardi 23 juillet 2019 14:51' // Differences $daysSinceEpoch = Carbon::createFromTimestamp(0)->diffInDays(); $daysUntilFuture = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT')->diffInDays();Mocking time with setTestNow()
masterFor testing purposes, you can mock the current time using
Carbon::setTestNow(). This allows you to simulate a specific point in time throughout your application. To return to the actual current time, callCarbon::setTestNow()without any arguments.<?php use Carbon\Carbon; // Mock 'now' to a specific date Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1)); // ... perform tests where Carbon::now() returns Jan 1, 2000 // Return to normal behavior Carbon::setTestNow();Create a CarbonTimeZone instance
masterYou can create a
CarbonTimeZoneinstance using several methods depending on your input type (string, integer, float, orDateTimeZone).- Constructor: Accepts a string, int, or float representing the timezone or offset.
instance(): A static factory method that safely converts mixed input into aCarbonTimeZone. Returnsnullif the input isnullorfalse.create(): An alias forinstance().createFromHourOffset(float $hourOffset): Creates a timezone from a decimal hour offset (e.g.,5.5for UTC+5:30).createFromMinuteOffset(float $minuteOffset): Creates a timezone from a total number of minutes offset.
use Carbon\CarbonTimeZone; // From a string identifier $tz = new CarbonTimeZone('America/New_York'); // From a numeric offset (e.g., 5.5 hours) $tz = CarbonTimeZone::createFromHourOffset(5.5); // Using the instance factory $tz = CarbonTimeZone::instance('UTC');Convert between offset strings and region names
masterThe
CarbonTimeZoneclass provides utilities to switch between geographic region names (e.g.,America/Toronto) and UTC offset strings (e.g.,+05:00).toOffsetName(?DateTimeInterface $date = null): Returns the current offset as a string in the formatsHH:MM(e.g.,+00:00or-12:30).toOffsetTimeZone(?DateTimeInterface $date = null): Returns a newCarbonTimeZoneinstance based on the current offset string.toRegionName(?DateTimeInterface $date = null, int $isDST = 1): Returns the first region string (likeAmerica/Toronto) that matches the current timezone. Returnsnullif no match is found.toRegionTimeZone(?DateTimeInterface $date = null): Returns a newCarbonTimeZoneinstance using the identified region name.
// Get offset string like '+02:00' $offsetString = $timezone->toOffsetName(); // Create a new timezone object from that offset $offsetTz = $timezone->toOffsetTimeZone(); // Get region name like 'Europe/Paris' $regionName = $timezone->toRegionName(); // Create a new timezone object from that region $regionTz = $timezone->toRegionTimeZone();Get abbreviated timezone names
masterYou can retrieve the abbreviated name of a timezone (e.g.,
EST,GMT) based on whether Daylight Saving Time (DST) is active.getAbbreviatedName(bool $dst = false): Returns the abbreviation. Set$dsttotrueto get the abbreviation used during DST.getAbbr(bool $dst = false): An alias forgetAbbreviatedName().
// Get abbreviation for standard time $abbr = $timezone->getAbbr(false); // e.g., 'EST' // Get abbreviation for daylight saving time $abbr = $timezone->getAbbr(true); // e.g., 'EDT'Get the timezone type
masterThe
getType()method returns an integer representing the type of timezone identifier used:- Type 1: A UTC offset (e.g.,
-0300). - Type 2: A timezone abbreviation (e.g.,
GMT). - Type 3: A timezone identifier (e.g.,
Europe/London).
- Type 1: A UTC offset (e.g.,
Cast CarbonTimeZone to other classes
masterThe
cast()method allows you to convert the currentCarbonTimeZoneinstance into another class, provided that the target class implements aninstance()method designed to handle the conversion.If the target class is a subclass of
DateTimeZonebut lacks aninstance()method,cast()will return a new instance of that class using the current timezone name.// Example: Casting to a specific DateTimeZone implementation if available $otherTz = $carbonTz->cast(SomeCustomDateTimeZone::class);Handle date parsing errors with ParseErrorException
masterWhen performing date string parsing operations in Carbon, a
ParseErrorExceptionmay be thrown if the input string does not match the expected format. This exception extendsInvalidArgumentExceptionand provides specific details about the mismatch.You can catch this exception to programmatically inspect what format was expected versus what was actually received, or to display a custom help message provided by the library.
Key methods for inspecting the error:
getExpected(): Returns the format string that was expected.getActual(): Returns the actual value that caused the failure (or 'data is missing' if the input was empty).getHelp(): Returns an additional help message describing how to resolve the error.
Use CarbonPeriodImmutable for immutable date periods
masterThe
CarbonPeriodImmutableclass extendsCarbonPeriodto provide a period where the individual date instances returned during iteration are immutable. By default, it usesCarbonImmutableas the date class for all iteration items. This ensures that any modifications to a date within the period do not affect the period itself or other dates in the sequence.use Carbon\CarbonPeriodImmutable; use Carbon\CarbonImmutable; // Example usage (conceptual based on class definition): // Creating a period where each step is a CarbonImmutable instance $period = CarbonPeriodImmutable::create('2023-01-01', '2023-01-05'); foreach ($period as $date) { // $date is an instance of CarbonImmutable echo $date->toDateTimeString() . PHP_EOL; }