Laravel framework provides the Carbon library to manage time events. There are numerous time display operations we can do using the Carbon library. Let’s go through this tutorial on how to display the time elapsed string, and the number of days left in Laravel.
Display Time Elapsed String – Carbon Library
We need to first import the Carbon library, as shown below.
use Carbon\Carbon;
Next, in the code snippet create a Carbon instance and pass the current date and time as shown below.
$startDate = Carbon::parse('2023-06-30 12:00:00');
Now, to find the remaining time, we can pass the code snippet given below.
$remainingTime = $startDate->diffForHumans();
The diffForHumans() method will return a human-readable form of the remaining time left. It will come in a string format as a time-elapsed string that keeps updating with time. For example, 2 days left, 3 weeks left, or so.
This feature is pretty useful in many applications. Suppose in newspapers, we see news published 8 hours ago, or 2 days ago, or an Instagram post from 2 hours ago. You can also create such types of applications using the Carbon library and the process stated above.
Display Time Elapsed String – Time Elapsed function
Laravel supports the time_elapsed_string
function. So another way to display the time elapsed is to simply echo or pass this function to a variable. The argument should be the date when an article was published. Calling the function, will manipulate from the date an article was published and the difference between the current time, and then show the total time elapsed since then. Consider the code snippet given below.
echo time_elapsed_string($n['datePublished']);