Carbon for PHP

repository·master·Indexed 41 days ago

https://github.com/carbonphp/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 creating instances, manipulating dates, mocking time for testing, and handling complex timezones via CarbonTimeZone.

Tokens
4.5K
Snippets
14
Records
18
Agent score
53%

What's inside Carbon

  1. Carbon for enterprise via Tidelift

    master
    Carbon is available as part of the Tidelift Subscription. This provides commercial support and maintenance for the package, helping enterprise users reduce risk and improve code health by paying maintainers directly through the Tidelift platform.
  2. Install Carbon without Composer

    master

    If you are not using Composer, you can install Carbon manually:

    1. Download the latest release from the GitHub releases page.
    2. Extract the contents of the ZIP archive into a directory within your project.
    3. Require the autoload.php file from that directory in your project to load Carbon and its dependencies.
    <?php
    require 'path-to-Carbon-directory/autoload.php';
    
    use Carbon//Carbon;
    
    printf("Now: %s", Carbon::now());
  3. Basic usage of Carbon

    master

    Carbon is an international extension for PHP's DateTime class. It provides a fluent API for creating, manipulating, and formatting dates and times.

    Creating instances

    • Carbon::now(): Gets the current date and time.
    • Carbon::now('America/Vancouver'): Gets the current time in a specific timezone.
    • Carbon::createFromDate(year, month, day): Creates a date from specific components.
    • Carbon::createFromTime(hour, minute, second, timezone): Creates a time from specific components.
    • Carbon::create(year, month, day, hour, minute, second, timezone): Creates a full date-time instance.
    • Carbon::parse('string'): Parses a date string.
    • Carbon::createFromTimestamp(timestamp): Creates an instance from a Unix timestamp.

    Manipulating dates

    Carbon allows for easy addition and subtraction of time units:

    • $date->addDay()
    • $date->subWeek()
    • $date->subMinutes(2)

    Formatting and Localization

    • toDateTimeString(): Returns a standard date-time string.
    • toRfc2822String(): Returns an RFC 2822 formatted string.
    • isoFormat('LLLL'): Returns a localized, human-readable format.
    • diffForHumans(): Returns a human-readable difference (e.g., '2 minutes ago').
    • locale('locale_code'): Sets the locale for the instance (e.g., zh_CN, fr_FR).

    Comparisons

    Comparisons are performed in UTC. You can use methods like:

    • gte($other): Greater than or equal to.
    • isWeekend(): Checks if the date falls on a weekend.

    Mocking time for testing

    To mock the current time (useful for unit testing), use setTestNow():

    // Mock now to a specific date
    Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
    
    // Return to real-time behavior
    Carbon::setTestNow();
    <?php
    
    use Carbon//Carbon;
    
    printf("Right now is %s", Carbon::now()->toDateTimeString());
    printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));
    
    $tomorrow = Carbon::now()->addDay();
    $lastWeek = Carbon::now()->subWeek();
    
    $officialDate = Carbon::now()->toRfc2822String();
    
    $howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
    
    $noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
    
    $internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');
    
    // Mocking time
    Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
    if (Carbon::now()->gte($internetWillBlowUpOn)) {
        die();
    }
    Carbon::setTestNow();
    
    if (Carbon::now()->isWeekend()) {
        echo 'Party!';
    }
    
    // Localization
    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')->isoFormat('LLLL'); // 'Tuesday, July 23, 2019 2:51 PM'
    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();
    $daysUntilInternetBlowUp = $internetWillBlowUpOn->diffInDays();
    Carbon::createFromTimestamp(0)->diffInDays($internetWillBlowUpOn);
  4. Install Carbon via Composer

    master

    To add Carbon to your PHP project 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 include the Composer autoloader in your PHP script to use Carbon classes:

    <?php
    require 'vendor/autoload.php';
    
    use Carbon//Carbon;
    
    printf("Now: %s", Carbon::now());
  5. Handle ParseErrorException when date parsing fails

    master

    The ParseErrorException is thrown by Carbon when a date string does not match the expected format during parsing operations. This exception extends InvalidArgumentException.

    When catching this exception, you can inspect the following methods to understand why the parsing failed:

    • getExpected(): Returns the format or pattern that was expected.
    • getActual(): Returns the actual value that was provided (or 'data is missing' if the input was empty).
    • getHelp(): Returns an additional help message provided during the exception construction.

    The error message follows the pattern: Format expected {expected} but {actual} {help}.

  6. Cast CarbonTimeZone to other classes

    master

    The cast(string $className) method allows you to convert the current CarbonTimeZone instance into another class.

    For the cast to work, the target $className must have an instance() method. If the target class is a subclass of DateTimeZone but lacks an instance() method, Carbon will attempt to return a new instance of that class using the current timezone name.

    use Carbon\CarbonTimeZone;
    
    $tz = new CarbonTimeZone('UTC');
    
    // Cast to a specific class that implements instance()
    // Note: The target class must have an instance() method
    $other = $tz->cast(SomeOtherTimeZoneClass::class);
  7. Get timezone abbreviation (DST aware)

    master

    You can retrieve the abbreviated name of a timezone (e.g., 'EST', 'GMT') using getAbbreviatedName() or its alias getAbbr(). This method allows you to specify whether Daylight Saving Time (DST) is active to ensure the correct abbreviation is returned.

    • $dst = true: Returns the abbreviation used during DST.
    • $dst = false: Returns the abbreviation used during standard time.
    use Carbon\CarbonTimeZone;
    
    $tz = new CarbonTimeZone('America/New_York');
    
    // Get abbreviation for standard time
    $abbr = $tz->getAbbr(false); // e.g., 'EST'
    
    // Get abbreviation for daylight saving time
    $abbr = $tz->getAbbr(true);  // e.g., 'EDT'
  8. Convert between Offset and Region names

    master

    CarbonTimeZone allows you to transition between an offset-based timezone (e.g., +02:00) and a region-based timezone (e.g., Europe/Paris).

    • toOffsetName(?DateTimeInterface $date = null): Returns the offset as a string (e.g., +02:00).
    • toOffsetTimeZone(?DateTimeInterface $date = null): Returns a new CarbonTimeZone instance representing the offset.
    • toRegionName(?DateTimeInterface $date = null, int $isDST = 1): Returns the first region string (like America/Toronto) that matches the current offset and DST status. Returns null if no match is found.
    • toRegionTimeZone(?DateTimeInterface $date = null): Returns a new CarbonTimeZone instance using the matched region name. If no region matches and Carbon::isStrictModeEnabled() is true, it throws an InvalidTimeZoneException.
    use Carbon\CarbonTimeZone;
    
    $tz = new CarbonTimeZone('America/New_York');
    
    // Get offset string
    $offset = $tz->toOffsetName(); // '-05:00'
    
    // Get a new timezone object based on the offset
    $offsetTz = $tz->toOffsetTimeZone();
    
    // Find the region name (e.g., 'America/New_York')
    $region = $tz->toRegionName();
    
    // Get a new timezone object based on the region
    $regionTz = $tz->toRegionTimeZone();
  9. Handle NotACarbonClassException for security

    master

    The NotACarbonClassException is thrown when an operation expects a class implementing CarbonInterface, but receives a different class. This is a security measure to prevent unpredictable behavior, especially when unserializing untrusted data.

    If you are certain that the class being used is safe, you can bypass this check using the allow() method. This method accepts a closure containing the logic that would otherwise trigger the exception.

    // Example of bypassing the check safely if you trust the input
    $result = NotACarbonClassException::allow(static fn () => $yourCarbonOperation);
  10. Instantiate CarbonTimeZone

    master

    You can create a CarbonTimeZone instance using the constructor or the instance() static method. The instance() method is more flexible as it handles various input types including DateTimeZone objects, strings, integers, floats, null, or false.

    Supported inputs:

    • Strings: Timezone identifiers (e.g., 'Europe/London') or offset strings (e.g., '+05:30').
    • Numeric values: Hour or minute offsets.
    • DateTimeZone: Existing PHP DateTimeZone objects.

    If the input is null or false, instance() returns null. If the timezone is invalid, it throws an InvalidTimeZoneException.

    use Carbon\CarbonTimeZone;
    
    // From string identifier
    $tz = new CarbonTimeZone('America/New_York');
    
    // From mixed input using instance()
    $tz = CarbonTimeZone::instance('+05:30');
    
    // Handling null/false
    $tz = CarbonTimeZone::instance(null); // returns null
  11. Create CarbonTimeZone from offsets

    master

    Carbon provides specialized static methods to create timezones based on numeric offsets (hours or minutes).

    • 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.
    • getOffsetNameFromMinuteOffset(float $minutes): A utility to convert a minute offset into a standardized string format like +HH:MM or -HH:MM.
    use Carbon\CarbonTimeZone;
    
    // Create from 5.5 hours
    $tz = CarbonTimeZone::createFromHourOffset(5.5);
    
    // Create from 330 minutes
    $tz = CarbonTimeZone::createFromMinuteOffset(330);
    
    // Get the string representation of an offset
    $offsetString = CarbonTimeZone::getOffsetNameFromMinuteOffset(330); // '+05:30'
  12. Validate CarbonInterface implementation with expectCarbonInterface()

    master

    The NotACarbonClassException::expectCarbonInterface(mixed $className) method can be used to programmatically verify if a given class name implements CarbonInterface.

    If the class does not implement the interface, it throws a NotACarbonClassException. Note that this check is subject to the TogglableDetection trait, meaning the exception might not be thrown if detection is disabled via the internal state of the exception class.

    use Carbon\Exceptions\NotACarbonClassException;
    
    // This will throw NotACarbonClassException if $className is not a CarbonInterface implementation
    NotACarbonClassException::expectCarbonInterface($className);