Carbon for PHP
repository·master·Indexed 41 days ago
https://github.com/carbonphp/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 creating instances, manipulating dates, mocking time for testing, and handling complex timezones via CarbonTimeZone.
What's inside Carbon
- 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.
Install Carbon without Composer
masterIf you are not using Composer, you can install Carbon manually:
- Download the latest release from the GitHub releases page.
- Extract the contents of the ZIP archive into a directory within your project.
- Require the
autoload.phpfile 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());Basic usage of Carbon
masterCarbon is an international extension for PHP's
DateTimeclass. 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);Install Carbon via Composer
masterTo add Carbon to your PHP project 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 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());Handle ParseErrorException when date parsing fails
masterThe
ParseErrorExceptionis thrown by Carbon when a date string does not match the expected format during parsing operations. This exception extendsInvalidArgumentException.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}.Cast CarbonTimeZone to other classes
masterThe
cast(string $className)method allows you to convert the currentCarbonTimeZoneinstance into another class.For the cast to work, the target
$classNamemust have aninstance()method. If the target class is a subclass ofDateTimeZonebut lacks aninstance()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);Get timezone abbreviation (DST aware)
masterYou can retrieve the abbreviated name of a timezone (e.g., 'EST', 'GMT') using
getAbbreviatedName()or its aliasgetAbbr(). 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'Convert between Offset and Region names
masterCarbonTimeZone 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 newCarbonTimeZoneinstance representing the offset.toRegionName(?DateTimeInterface $date = null, int $isDST = 1): Returns the first region string (likeAmerica/Toronto) that matches the current offset and DST status. Returnsnullif no match is found.toRegionTimeZone(?DateTimeInterface $date = null): Returns a newCarbonTimeZoneinstance using the matched region name. If no region matches andCarbon::isStrictModeEnabled()is true, it throws anInvalidTimeZoneException.
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();Handle NotACarbonClassException for security
masterThe
NotACarbonClassExceptionis thrown when an operation expects a class implementingCarbonInterface, 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);Instantiate CarbonTimeZone
masterYou can create a
CarbonTimeZoneinstance using the constructor or theinstance()static method. Theinstance()method is more flexible as it handles various input types includingDateTimeZoneobjects, strings, integers, floats,null, orfalse.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
DateTimeZoneobjects.
If the input is
nullorfalse,instance()returnsnull. If the timezone is invalid, it throws anInvalidTimeZoneException.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- Strings: Timezone identifiers (e.g.,
Create CarbonTimeZone from offsets
masterCarbon 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.5for 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:MMor-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'Validate CarbonInterface implementation with expectCarbonInterface()
masterThe
NotACarbonClassException::expectCarbonInterface(mixed $className)method can be used to programmatically verify if a given class name implementsCarbonInterface.If the class does not implement the interface, it throws a
NotACarbonClassException. Note that this check is subject to theTogglableDetectiontrait, 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);