×


Date Time in Laravel and PHP with Carbon

Carbon is a package which extends PHP's own DateTime class by providing some nice functionality to deal with dates in PHP.

This nifty package called Carbon can help make dealing with date/time in PHP much easier and more semantic so that our code can become more readable and maintainable.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to resolve PHP related errors.

In this context, we shall look into how to manage Date/Time easily in Laravel and PHP with Carbon.


How to setup Carbon?

Carbon is already included in Laravel. 

Thus, whenever we need to use Carbon, we can import it like:

<?php
use Carbon\Carbon;

Now we can use this package to perform various activities. 

For instance, to obtain a Specific Date/Time we can use any of the formats below:

// get the current time

$current = Carbon::now();
$current = new Carbon();

// get today

$today = Carbon::today();

// get yesterday

$yesterday = Carbon::yesterday();

// get tomorrow

$tomorrow = Carbon::tomorrow();

// parse a specific string

$newYear = new Carbon('first day of January 2021');

// set a specific timezone

$newYearPST = new Carbon('first day of January 2021', 'America\Pacific');


How to create Dates from specific arguments ?

In addition to the quick ways to define date/times, Carbon also lets us create date/times from a specific number of arguments:

Carbon::createFromDate($year, $month, $day, $tz);
Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

If we pass in null for any of those attributes, it will default to current.


How to manipulate the Date/Time ?

While working with date/time we may often need to manipulate the date or time.

For instance, when creating a trial period for a user, we will want the trial period to expire after a certain amount of time. 

So let us say we have a 30 day trial period. We could easily calculate that time with add and subtract.

For this trial period, we would do:

// get the current time

$current = Carbon::now();

// add 30 days to the current time

$trialExpires = $current->addDays(30);

From the Carbon docs, here are some of the other add() and sub() methods available to us:

$dt = Carbon::create(2020, 1, 31, 0);
echo $dt->toDateTimeString(); // 2020-01-31 00:00:00
echo $dt->addYears(5); // 2025-01-31 00:00:00
echo $dt->addYear(); // 2026-01-31 00:00:00
echo $dt->subYear(); // 2025-01-31 00:00:00
echo $dt->subYears(5); // 2020-01-31 00:00:00
echo $dt->addMonths(60); // 2025-01-31 00:00:00
echo $dt->addMonth(); // 2025-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps
echo $dt->subMonth(); // 2025-02-03 00:00:00
echo $dt->subMonths(60); // 2020-02-03 00:00:00
echo $dt->addDays(29); // 2020-03-03 00:00:00
echo $dt->addDay(); // 2020-03-04 00:00:00
echo $dt->subDay(); // 2020-03-03 00:00:00
echo $dt->subDays(29); // 2020-02-03 00:00:00
echo $dt->addWeekdays(4); // 2020-02-09 00:00:00
echo $dt->addWeekday(); // 2020-02-10 00:00:00
echo $dt->subWeekday(); // 2020-02-09 00:00:00
echo $dt->subWeekdays(4); // 2020-02-03 00:00:00
echo $dt->addWeeks(3); // 2020-02-24 00:00:00
echo $dt->addWeek(); // 2020-03-02 00:00:00
echo $dt->subWeek(); // 2020-02-24 00:00:00
echo $dt->subWeeks(3); // 2020-02-03 00:00:00
echo $dt->addHours(24); // 2020-02-04 00:00:00
echo $dt->addHour(); // 2020-02-04 01:00:00
echo $dt->subHour(); // 2020-02-04 00:00:00
echo $dt->subHours(24); // 2020-02-03 00:00:00
echo $dt->addMinutes(61); // 2020-02-03 01:01:00
echo $dt->addMinute(); // 2020-02-03 01:02:00
echo $dt->subMinute(); // 2020-02-03 01:01:00
echo $dt->subMinutes(61); // 2020-02-03 00:00:00
echo $dt->addSeconds(61); // 2020-02-03 00:01:01
echo $dt->addSecond(); // 2020-02-03 00:01:02
echo $dt->subSecond(); // 2020-02-03 00:01:01
echo $dt->subSeconds(61); // 2020-02-03 00:00:00


Getters and Setters

Another quick way to manipulate or read the time is to use the getters and setters available:

$dt = Carbon::now();

// set some things

$dt->year = 2015;
$dt->month = 04;
$dt->day = 21;
$dt->hour = 22;
$dt->minute = 32;
$dt->second = 5;

// get some things

var_dump($dt->year);
var_dump($dt->month);
var_dump($dt->day);
var_dump($dt->hour);
var_dump($dt->second);
var_dump($dt->dayOfWeek);
var_dump($dt->dayOfYear);
var_dump($dt->weekOfMonth);
var_dump($dt->daysInMonth);

We can even string together some setters:

$dt = Carbon::now();
$dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString();
$dt->setDate(1975, 5, 21)->setTime(22, 32, 5)->toDateTimeString();
$dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();


Finding the Difference

There are methods available in Carbon to find the difference in time. 

Some among them are listed below:

$current = Carbon::now();
$dt = Carbon::now();
$dt = $dt->subHours(6);
echo $dt->diffInHours($current); // -6
echo $current->diffInHours($dt); // 6
$future = $current->addMonth();
$past = $current->subMonths(2);
echo $current->diffInDays($future); // 31
echo $current->diffInDays($past); // -62


Relative Time

The diff() method helps us to display relative time. For instance, if we want to display the published time of a blog in a relative manner like 3 hours ago instead of the actual timestamp, we could use the diffForHumans() method. 

Some of the usages for the method include:

$dt = Carbon::now();
$past = $dt->subMonth();
$future = $dt->addMonth();
echo $dt->subDays(10)->diffForHumans(); // 10 days ago
echo $dt->diffForHumans($past); // 1 month ago
echo $dt->diffForHumans($future); // 1 month before


[Need urgent assistance in fixing PHP errors? – We're available 24*7. ]


Conclusion

This article covers how to manage date/time easily in Laravel and PHP with Carbon. Basically, Carbon is a package that helps us to deal with date/time in Laravel and PHP in a much easier and systematic manner.

Working with date and time in PHP is not the easiest or most clear of tasks. We have to deal with strtotime, formatting issues, lots of calculations, and more.


Carbon provides some nice functionality to deal with dates in PHP such as:

1. Dealing with timezones

2. Getting current time easily

3. Converting a datetime into something readable

4. Parse an English phrase into datetime (first day of January 2016)

5. Add and Subtract dates (+ 2 weeks, -6 months)

6. Semantic way of dealing with dates


Carbon is already included in Laravel so there's no need to go and add it with Composer.

Whenever we need to use Carbon, we can import it like so:

<?php

use Carbon\Carbon;

After importing you can do a lot with this great package.