Some times in online news paper we see, the news published 5 hours ago, or 1 day ago, which is more informative and easy to process other than displaying date and time in non-user friendly format. We can implement similar behavior by adding a time elapsed string function to our Laravel application.
I came across such requirement of showing time in a format from which users can see how many hours before an article had been published on a blog.
Time Elapsed String Examples
Lets discuss some code examples, which will work both in Laravel and non-Laravel applications for time elapsed strings.
Time Elapsed function – Example
Laravel supports the function time_elapsed_string
. So you can simply echo or pass this function to a variable. The argument should be the date when article was published. When the function is called, it will manipulate from the date an article was published and the difference between the current time, and show the total time elapsed since then.
echo time_elapsed_string($n['datePublished']);
Case 2:
The function below will process updated_at column value from database table, if its not NULL, getUpdateTimeAttribute()
will process updated_at timestamp and will return value. For example, 2 hours ago. Otherwise it will return null.
public function getUpdateTimeAttribute()
{
if ($this->updated_at != NULL) {
return time_elapsed_string($this->updated_at);
}
return null;
}
Case 3:
The function takes in a value which you may pass as the time and date when the article was published. It will then process the timestamp in that variable and return a time elapsed value. For example, 4 hours ago, or return null if the variable doesn’t exists or is empty.
public function timeElapsed(){
if ($this->value) {
return time_elapsed_string($this->value);
}
return null;
}
In addition to these, you may also use the PHP Carbon Library to subtract days from current date.