How To

How to Manage DateTime with Carbon in Laravel and PHP?

Hello Laravel Friends,

Today we will learn about managing date and time with Carbon in Laravel and PHP.

Sooner or later you surely need to work with date and time with the Laravel application. Working with date and time sometimes becomes complicated. You face formatting issues, adding and subtracting date, and more.

Here comes the use of Laravel Carbon.

What is Carbon in Laravel?

Carbon is a PHP package that can help make dealing with date and time in PHP much easier. Laravel Carbon deals with the following things:

  • Creating date and time
  • Getting current time zone
  • Adding and subtracting time
  • Calculate time differences
  • Convert date and time into readable format

So let’s start with Laravel Carbon tutorial

Prerequisites for Laravel Carbon

A working Laravel development environment

Setting Up the Project with Carbon PHP Laravel

Before using carbon, you need to import carbon from the carbon namespace. Carbon is already included in Laravel. So whenever we need to use Carbon, we can import it like below

<?php
use Carbon/Carbon;

Getting a specific Date and time using Carbon

Get the current time

echo  Carbon::now();

Get today’s date

echo  Carbon::today();

Get yesterday’s date

echo Carbon::yesterday();

Get tomorrow’s date

echo Carbon::tomorrow();

Get the date from the string

echo new Carbon('first day of January 2022');

The output will be as follows

2022-01-01 00.00.00

Creating Date and Time using Laravel Carbon

Carbon also creates date and time from the specific number of arguments.

createFromDate() accepts $year, $month, $day, $tz(time zone)

Carbon::createFromDate($year, $month, $day, $tz);

createFromTime() accepts $hour, $minute, $second, and $tz (time zone)

Carbon::createFromTime($hour, $minute, $second, $tz);

create() accepts $year, $month, $day, $hour, $minute, $second, $tz (time zone)

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

Manipulating the Date and Time

Getting a date and time is not enough. You need to manipulate the date and time.

For example, when creating a trial period for users, you can calculate that trial period using carbon’s add and subtract.

$current = Carbon::now();
$trialExpires = $current->addDays(7);

Consider a date

$date = Carbon::create(2022, 8, 24, 0);

Modifying the date with addYears() and subYears()

Command Output
echo $date->addYear(); 2023-08-24 00:00:00
echo $date->addYears(5); 2027-08-24 00:00:00
echo $date->subYear(); 2021-08-24 00:00:00
echo $date->subYears(5); 2017-08-24 00:00:00

Modifying the date with addMonths() and subMonths()

Command Output
echo $date->addMonth(); 2022-09-24 00:00:00
echo $date->addMonths(5); 2023-02-24 00:00:00
echo $date->subMonth(); 2023-01-24 00:00:00
echo $date->subMonths(5); 2022-08-24 00:00:00

Modifying the date with addDays() and subDays()

Command Output
echo $date->addDay(); 2022-08-25 00:00:00
echo $date->addDays(5); 2022-08-30 00:00:00
echo $date->subDay(); 2022-08-29 00:00:00
echo $date->subDays(5); 2022-08-24 00:00:00

Modifying the date with addWeekdays() and subWeekdays()

Command Output
echo $date->addWeekday(); 2022-08-25 00:00:00
echo $date->addWeekdays(5); 2022-09-01 00:00:00
echo $date->subWeekday(); 2022-08-31 00:00:00
echo $date->subWeekdays(5); 2022-08-24 00:00:00

Modifying the date with addWeeks() and subWeeks()

Command Output
echo $date->addWeek(); 2022-08-31 00:00:00
echo $date->addWeeks(5); 2022-10-05 00:00:00
echo $date->subWeek(); 2022-09-28 00:00:00
echo $date->subWeeks(5); 2022-08-24 00:00:00

Modifying the date with addHours() and subHours() will result in the following:

Command Output
echo $date->addHour(); 2022-08-24 01:00:00
echo $date->addHours(5); 2022-08-24 06:00:00
echo $date->subHour(); 2022-08-24 05:00:00
echo $date->subHours(5); 2022-08-24 00:00:00

Modifying the date with addMinutes() and subMinutes()

Command Output
echo $date->addMinute(); 2022-08-24 00:01:00
echo $date->addMinutes(5); 2022-08-24 00:06:00
echo $date->subMinute(); 2022-08-24 00:05:00
echo $date->subMinutes(5); 2022-08-24 00:00:00

Modifying the date with addSeconds() and subSeconds()

Command Output
echo $date->addSecond(); 2022-08-24 00:00:01
echo $date->addSeconds(5); 2022-08-24 00:00:06
echo $date->subSecond(); 2022-08-24 00:00:05
echo $date->subSeconds(5); 2022-08-24 00:00:00

Formatting Date and Time

toXXXString() methods are available in PHP to display dates and times with predefined formatting

Command Output
echo $date->toDateString(); 2022-08-24
echo $date->toFormattedDateString(); Aug 24, 2022
echo $date->toTimeString(); 00:00:00
echo $date->toDateTimeString(); 2022-08-24 00:00:00
echo $date->toDayDateTimeString(); Wed, Aug 24, 2022 12:00 AM

Calculating Relative Time

diff() methods is used in Carbon to display time relatively.

Finding the Difference

Consider the following example:

$date      = Carbon::create(2022, 8, 24, 0);
$future  = Carbon::create(2022, 8, 24, 0);
$past    = Carbon::create(2022, 8, 24, 0);

Results of diffInHours():

$future = $future->addHours(6);
$past   = $past->subHours(6);
Command Output
echo $date->diffInHours($future); 6
echo $date->diffInHours($past); 6

Results of diffInDays():

$future  = $future->addMonth();
$past    = $past->subMonths(2);
Command Output
echo $date->diffInDays($future); 31
echo $date->diffInDays($past); 61

Displaying the Difference for Humans

Displaying time relatively can sometimes be more useful to readers than a date or timestamp.

The diffForHumans() method is used for calculating the difference and also converting it to a humanly readable format.

$date      = Carbon::create(2022, 8, 24, 0);
$future  = Carbon::create(2022, 8, 24, 0);
$past    = Carbon::create(2022, 8, 24, 0);
$future  = $future->addMonth();
$past    = $past->subMonths(2);
Command Output
echo $date->diffForHumans($future); 1 month before
echo $date->diffForHumans($past); 2 months after

Wrap up

Hence, this article can be useful to get idea about PHP Laravel Carbon and manage date and time in Laravel using Carbon. To learn more about Laravel, you can connect with our experienced Laravel developers. If you found the Laravel Carbon tutorial useful, share it with your friends and hit the 5 stars.

Happy Reading!

Click to rate this post!
[Total: 11 Average: 4.1]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer 🏅 with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket 🏏.

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

5 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

7 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

7 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

1 week ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago