Carbon PHP Extension

repository·master·Indexed 12 days ago

https://github.com/briannesbitt/carbon

An 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().

Tokens
3.4K
Snippets
12
Records
17
Agent score
97%

What's inside Carbon

  1. Carbon Enterprise Support via Tidelift

    master
    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.
  2. Install Carbon via Composer

    master

    The recommended way to install Carbon is using Composer. Run the following command in your terminal:

    $ composer require nesbot/carbon

    Alternatively, you can manually add it to your composer.json file:

    {
        "require": {
            "nesbot/carbon": "^3"
        }
    }

    After installation, ensure you require the Composer autoloader in your PHP script to use Carbon classes.

  3. Install Carbon without Composer

    master

    If 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.php file 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());
  4. Basic usage of Carbon

    master

    Carbon extends PHP's DateTime class to provide an easier, more expressive API for date and time manipulation. You can create instances using now(), parse(), create(), or createFromDate(). 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();
  5. Mocking time with setTestNow()

    master

    For 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, call Carbon::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();
  6. Create a CarbonTimeZone instance

    master

    You can create a CarbonTimeZone instance using several methods depending on your input type (string, integer, float, or DateTimeZone).

    • Constructor: Accepts a string, int, or float representing the timezone or offset.
    • instance(): A static factory method that safely converts mixed input into a CarbonTimeZone. Returns null if the input is null or false.
    • create(): An alias for instance().
    • createFromHourOffset(float $hourOffset): Creates a timezone from a decimal hour offset (e.g., 5.5 for 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');
  7. Convert between offset strings and region names

    master

    The CarbonTimeZone class 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 format sHH:MM (e.g., +00:00 or -12:30).
    • toOffsetTimeZone(?DateTimeInterface $date = null): Returns a new CarbonTimeZone instance based on the current offset string.
    • toRegionName(?DateTimeInterface $date = null, int $isDST = 1): Returns the first region string (like America/Toronto) that matches the current timezone. Returns null if no match is found.
    • toRegionTimeZone(?DateTimeInterface $date = null): Returns a new CarbonTimeZone instance 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();
  8. Get abbreviated timezone names

    master

    You 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 $dst to true to get the abbreviation used during DST.
    • getAbbr(bool $dst = false): An alias for getAbbreviatedName().
    // 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'
  9. Cast CarbonTimeZone to other classes

    master

    The cast() method allows you to convert the current CarbonTimeZone instance into another class, provided that the target class implements an instance() method designed to handle the conversion.

    If the target class is a subclass of DateTimeZone but lacks an instance() 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);
  10. Handle date parsing errors with ParseErrorException

    master

    When performing date string parsing operations in Carbon, a ParseErrorException may be thrown if the input string does not match the expected format. This exception extends InvalidArgumentException and 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.
  11. Use CarbonPeriodImmutable for immutable date periods

    master

    The CarbonPeriodImmutable class extends CarbonPeriod to provide a period where the individual date instances returned during iteration are immutable. By default, it uses CarbonImmutable as 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;
    }