Laravel bundles Carbon (https://github.com/briannesbitt/Carbon), which extends and augments PHP's native DateTime
object with more expressive methods. Laravel uses it mainly to provide more expressive methods on the date and time properties (created_at
, edited_at
, and deleted_at
) of an Eloquent object. However, since the library is already there, it would be a shame not to use it elsewhere in the code of your application.
Carbon objects are meant to be instantiated like normal DateTime objects. They do, however, support a handful of more expressive methods.
Carbon objects can be instantiated using the default constructor that will use the current date and time:
$now = new Carbon();
They can be instantiated using the current date and time in a given timezone:
$jetzt = new Carbon('Europe/Berlin');
They can be instantiated using expressive methods:
$yesterday = Carbon::yesterday();
$demain = Carbon::tomorrow("Europe/Paris");
They can be instantiated using exact parameters:
Carbon::createFromDate($year, $month, $day, $tz);
Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
We can generate human-readable relative timestamps such as 5 minutes ago, last week, or in a year with the diffForHumans()
method:
$post = Post::find(123); echo $post->created_at->diffForHumans();
Carbon also provides a handful of simple and expressive methods that will come in handy in your controllers and views:
$date->isWeekday();
$date->isWeekend();
$date->isYesterday();
$date->isToday();
$date->isTomorrow();
$date->isFuture();
$date->isPast();
$date->isLeapYear();