How to Manage Dates and Times in PHP Using Carbon

How to Manage Dates and Times in PHP Using Carbon

Date and time manipulation is one of a few frequently-experienced challenges of developing web apps in PHP. And one of it's most prevalent issues is identifying time disparities and making them readable, such as "one hour ago".

However, handling dates and times — and issues such as this — is greatly simplified by using Carbon; it's a library which reduces lengthy hours of coding and debugging to only a few lines of code. This is because Carbon, created by Brian Nesbit, extends PHP's own DateTime class and makes it much simpler to use.

If you've not heard of it before, it is self-described as:

A basic PHP API extension for DateTime

In this tutorial, you will learn Carbon's core features and capabilities, giving you the ability to far more easily manipulate date and time in PHP.

Prerequisites

To follow this tutorial you need the following components:

  • PHP 7.4 or higher.
  • Composer globally installed.

Installation

To install Carbon, first create a new project directory called carbon, change into the directory, and install the package, by executing the following commands:

mkdir carbon
cd carbon
composer require nesbot/carbon

!!!tip

Carbon is already included if you're using Laravel. If you are, have a look at the suggested Laravel settings and best practices. If you're using Symfony, have a look at the Symfony configuration and best-practices guidelines.

!!!tip

Format dates using Carbon

With Carbon installed, in your editor or IDE, create a new PHP file, named index.php in the root of your project directory. Then, add the code below to index.php to include Composer's Autoloader file, vendor/autoload.php, and imported Carbon's core class.

<?php 
require 'vendor/autoload.php';
use Carbon\Carbon;

Print dates

Now that Carbon's installed, let's start working through some examples, starting with the most essential: printing out some dates. To do that, we'll use carbon::today to retrieve today's date via Carbon, which you can see in the example below.

<?php

require __DIR__ . "/vendor/autoload.php";

echo carbon::today() . "\n";

Add that to index.php and then run it.

2021-10-25 00:00:00

The output, which you can see an example of above, returns the current date, with the time being blank. However, if you update index.php to use carbon:: now instead, which you can see in the example below, you can retrieve the time along with the date.

<?php

require __DIR__ . "/vendor/autoload.php";

$now = carbon::now()
echo "$now\n";

After updating index.php and running it, you should see output similar to the example below, in your terminal.

2021-01-25 22:49:56

In contrast to Carbon::now() which returns the current date and time, and Carbon:today() which only returns the current date, Carbon::yesterday() and Carbon::tomorrow() generate Carbon instances for yesterday and tomorrow, respectively, as in the examples below.

<?php

require __DIR__ . "/vendor/autoload.php";

$yes = Carbon::yesterday();
echo "Yesterday: $yes\n";

$tomorrow = Carbon::tomorrow();
echo "Tomorrow: $tomorrow\n";

The functions today(), yesterday(), now, and tomorrow() are examples of common static instantiation helpers.

Create dates with precision

Carbon also allows us to generate dates and times based on a set of parameters. For example, to create a new Carbon instance for a specific date use the Carbon::createFromDate() method, passing in the year, month, day, and timezone, as in the following example.

<?php

require __DIR__ . "/vendor/autoload.php";

$year = 2020;
$month = 08;
$day = 21;
$timezone = 'Europe/Berlin';
Carbon::createFromDate($year, $month, $day, $timezone);

You can also specify the time, by calling Carbon::create(), passing in the year, month, day, timezone, hour, minute, and second, as in the following example

<?php

require __DIR__ . "/vendor/autoload.php";

$year = 2021;
$month = 04;
$day = 21;
$timezone = 'Europe/Berlin';
$hour = 11;
$minute = 11;
$second = 11;
Carbon::create($year, $month, $day, $hour, $minute, $second, $timezone);

If any one or more of $year, $month, $day, $hour, $minute, or $second are set to null their now() equivalent values will be used. If $hour is not null, however, then the default values for $minute and $second will be 0.

If you pass in null for any of those attributes, it will default to the current date and time.

Update index.php in your editor or IDE to match the code below and run it.


<?php

require __DIR__ . "/vendor/autoload.php";

use Carbon\Carbon;

$date1 = Carbon::create(2021,10, 25, 12, 48, 00);
echo $date1 . "\n";

$date2 = Carbon::create(2021, 8, 25, 22, 48, 00, 'Europe/Moscow');
echo $date2 . "\n";

$date3 = Carbon::createFromDate(2018, 8, 14, 'America/Chicago');
echo $date3 . "\n";

$date4 = Carbon::createFromDate(2021,10, 25, 'Africa/Lagos');
$date5 = Carbon::createFromTimestamp(1633703084);
echo $date5. "\n";

The create() function in the first variable creates a Carbon instance from date and time components; A timezone was supplied on the constructor to the second variable.

A Carbon object was constructed using date components with Carbon::createFromDate() when initializing the third and fourth variables. Doing so generates a Carbon instance based on just on a date.

It's worth pointing out that if no timezone is specified, your default timezone is used. However, if a timezone other than yours is specified, the timezone's actual time is supplied. The current time is set in the time section.

The final variable, initialized using Carbon::createFromTimestamp, generates a date based on a timestamp.

Relative Modifiers

Another fantastic feature of Carbon is relative modifiers. These allow strings such as "next friday" or "a year ago" to be used when constructing Carbon instances relative to the current date.

The following are examples of strings that are considered relative modifiers.

  • +
  • -
  • ago
  • first
  • next
  • last
  • this
  • today
  • tomorrow

    Modify the date and time

When working with dates, you'll need to do more than just get the date and time. You'll frequently need to modify the date or time as well, such as adding a day or a week or subtracting a month.

A good example of needing this functionality is when building an affiliate program. In this scenario you'll want the affiliate cookie which the user receives to expire after a specified period of time, making the referral invalid.

Let's assume a cookie has a 90-day lifespan. With Carbon's add and subtract methods, we could compute that time quite trivially. The example below uses addDays() to determine when the cookie expires.

<?php

require __DIR__ . "/vendor/autoload.php";

$name = 'Affliate_Program';
$value = 'Referrer ID';
$path = '/';
$current = Carbon::now();

// add 90 days to the current time
$time = $current->addDays(90);
$expires = strtotime($time);
setcookie($name, $value, $expires, $path);

It also uses some of the other add() and sub() methods which Carbon provides. If you're adding a single date, such as a day, you use addDay(), but if you're adding several days, you use addDays(). Using Carbon’s add and subtract methods can provide you with adjusted date and times.

Looking forward and back

Carbon also provides the next() and previous() functions which return the upcoming and previous occurrences of a particular weekday, which you can see an example of in the code below.

<?php

require __DIR__ . "/vendor/autoload.php";

use Carbon\Carbon;

$now = Carbon::now();
echo "$now\n";

$next_monday = $now->next(Carbon::MONDAY);
echo "Next monday: $next_monday\n";

$prev_monday = $now->previous(Carbon::MONDAY);
echo "Previous monday: $prev_monday\n";

Format the date and time

Yet another fantastic option Carbon provides is the ability to format dates and times in whatever format that you desire.

As Carbon is an expanded version of PHP's built-in date and time functions, Carbon can use PHP's built-in date formats via the format() function. In addition, toXXXString() methods are available to display dates and times with predefined formatting.

<?php

require __DIR__ . "/vendor/autoload.php";

$dt = Carbon::create(2021,10, 25, 12, 48, 00);
echo $dt->toDateString();//2021-10-25
echo $dt->toFormattedDateString();//Oct 25, 2021
echo $dt->toTimeString();//12:48:00
echo $dt->toDateTimeString();//2021-10-25 12:48:00
echo $dt->toDayDateTimeString();//Mon, Oct 25, 2021 12:48 PM
echo $dt->format('Y-m-d h:i:s A');//2021-10-25 12:48:00 PM

Other typical datetime formatting methods available to Carbon include the following.

<?php

require __DIR__ . "/vendor/autoload.php";

$dt->toAtomString();
$dt->toCookieString();
$dt->toIso8601String();
$dt->toIso8601ZuluString();
$dt->toRfc822String();
$dt->toRfc850String(); 
$dt->toRfc1036String();
$dt->toRfc1123String();
$dt->toRfc3339String(); 
$dt->toRfc7231String(); 
$dt->toRssString();
$dt->toW3cString();

Calculate relative time

The diffForHumans() functions in Carbon also allow us to represent time in relative terms. Datetime discrepancies are frequently displayed in a so-called humanized format, such as in one year or three minutes ago.

Let's assume we're developing an extension for a blog CMS and we want to display the article's publish time in "hours ago" or the comments publish time in "hours ago."

First, the time and date the article was published, as well as other parameters, would be recorded in a database field. As a result, we extract the date from the database in the format Y-m-d H:i:s and store it in a variable. Let's call it $time.


<?php

$time = $row['articledate'];

If the date in our database is August 4th, 2021, such as in the example below, you would use the carbonCreateFromFormat() function to produce a Carbon date, and then use diffForHumans() to find the difference.

<?php

require __DIR__ . "/vendor/autoload.php";

$row['articledate'] = 2021-08-04 16:19:49;
$dt = Carbon::createFromFormat('Y-m-d H:i:s', $time);

echo $dt->diffForHumans() . "\n";

If the date was saved as a timestamp, you can call Carbon::createFromTimestamp. Carbon also provides user translator services. So if your site makes use of a user's language preferences, call the language. If you have a user that speaks French, for example, all you have to do is call the function before the code, as seen below.

<?php

require __DIR__ . "/vendor/autoload.php";

Carbon::setLocale()'.Carbon::setLocale('fr');
echo $dt->diffForHumans() . "\n";

Output in this case would be, for example, 'il y a 2 mois'.

That's the essentials of managing dates and times in PHP using Carbon

In this tutorial, you learned how to install Carbon and its core functionality. However, Carbon has a great deal more functionality than has been covered in this tutorial. Check out their docs if you're keen to learn more about the available functionality.