Many times during application development in Laravel, you might need to work with dates and times. Managing dates and times can be ridiculously complex at times, most importantly because of different time zones.
The Carbon PHP API extension for DateTime serves as the solution here. Laravel uses this API by default. Let us see how we can use the Carbon API to o calculate the remaining days and even show up negative days if a specific date has passed. To use carbon, you should first understand what the API actually is.
What is Carbon?
A PHP package that can deal with times and time zones and has many more use cases, for example:
- Creates dates and times
- Convert dates and times to different time zones
- Manipulating (Adding and subtracting) times
- Calculates time differences
- Converts dates and times into human-readable formats.
To learn on how to add Carbon API and use it in Laravel, refer to the tutorial on How to use Carbon in Laravel.
Calculate remaining days using Carbon
In some applications, you need to display the remaining days for a product or website launch. For example, 10 days left for new product and so.
In such applications, you need an algorithm to automatically calculate the date difference and display the remaining days accordingly. When creating such applications with Laravel, Carbon API is the best solution. Most importantly, as it manages all time zones, it can show more accurate results for a website when accessed from anywhere around the world.
To calculate the difference between two dates (i.e. the current date and the one for which you are calculating the remaining days) you can use Carbon in following ways.
$start = Carbon::parse('2022-07-30');
$end = Carbon::parse('2022-05-06');
$diff = $start->diffInDays($end);
The code above will give you the difference between this $start
and $end
dates and use the diffInDays
method to convert that difference in days. Here, in place of the static date 2022-07-30
, You can pass an object or array values. For example, $start = Carbon::parse($user->date_start);
But, to find the difference, in this case you may use the code below.
$end = Carbon::parse($patient->date_end);
{{ \Carbon\Carbon::now()->diffInDays($end) }}
If the end date has passed, an you need to view the difference in negative values. you will have to pass false
as the second parameter of the diffInDays
function as shown below.
Carbon\Carbon::now()->diffInDays($patient->date_end, false)