Laravel has carbon
library to get the current date time and format in laravel and also we can use core php date
functions to fetch the date and time. After php 5, php also introduced DateTime
class to conduct the operations of date time related functionality. Sometimes in our application we want to use current date, time and day to compare the past or future date or to show specific time so we can either use carbon
library or core php DateTime
class.
This example will work in all version of laravel including laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9. In example we will show date and time with Carbon
, DateTime
class and core php date()
function.
Also Read : How to Change Date Format in Laravel ?
Let’s begin the tutorial of Get Current Date Time and format in Laravel So to print current date time in laravel we can use as follow
Method 1 : Using Carbon to get Date Time
In this method we will use carbon class as follow
$dattime = \Carbon\Carbon::now();
echo $dattime->toDateTimeString();
this will output the date in format Y-m-d H:i:s
so the output will be
2022-09-02 02:23:19
Another way to get the information is as follow
$date = \Carbon\Carbon::now();
return $date->toArray();
And output
{ "year": 2022, "month": 9, "day": 2, "dayOfWeek": 5, "dayOfYear": 245, "hour": 2, "minute": 26, "second": 16, "micro": 505774, "timestamp": 1662085576, "formatted": "2022-09-02 02:26:16", "timezone": { "timezone_type": 3, "timezone": "UTC" } }
Method 2 : Using date function to get Date Time
In this method we will use date()
core function class as follow
$dattime = date("Y-m-d H:i:s");
echo $dattime;
this will output the date in format Y-m-d H:i:s
and we can change in any date format so the output will be
2022-09-02 02:23:19
Method 3 : Using DateTime class to get Date Time
In this method we will use DateTime()
class class as follow
$datetime = new DateTime();
echo $datetime->format('Y-m-d H:i:s');
this will output the date in format Y-m-d H:i:s
and we can change in any date format so the output will be
2022-09-02 02:23:19