Getting current date, time, and day in Laravel [duplicate]
Asked Answered
G

22

186

I need to get the current date, time, and day using Laravel.

I tried to echo $ldate = new DateTime('today'); and $ldate = new DateTime('now');

But it is always returning 1.

How can I get the current date, time, and day?

Glennglenna answered 23/1, 2015 at 11:44 Comment(1)
I think the main problem is that you're doing echo $now = new DateTime(); whereas instead you should just set the variable without the echo (i.e. do $now = new DateTime();) and then when you want to echo it you need to use the format() method (docs): echo $now->format('Y-m-d');Winwaloe
G
322

Laravel has the Carbon dependency attached to it.

Carbon::now(), include the Carbon\Carbon namespace if necessary.

Edit (usage and docs)

Say I want to retrieve the date and time and output it as a string.

$mytime = Carbon\Carbon::now();
echo $mytime->toDateTimeString();

This will output in the usual format of Y-m-d H:i:s, there are many pre-created formats and you will unlikely need to mess with PHP date time strings again with Carbon.

Documentation: https://github.com/briannesbitt/Carbon

String formats for Carbon: http://carbon.nesbot.com/docs/#api-formatting

Gascon answered 23/1, 2015 at 11:57 Comment(4)
use Carbon\Carbon; is the namespace declarationStrage
how to extract dayname from 2016/2/20 in laravel 5?? please replyRameau
@Glennglenna Use Carbon::now()->format('d-m-Y')Suffer
catch up on your Carbon documentation. No one will write code for you. The answer provides what was asked by the OP.Ekaterina
K
102

Try this,

$ldate = date('Y-m-d H:i:s');
Kowalski answered 23/1, 2015 at 11:46 Comment(8)
This is the kind of php way, how can i go for laravel wayGlennglenna
@Chennai Why do you need it to do the "laravel" way? Laravel is the "php way" :)Tadeas
When you have access to classes like Carbon that are fully tested it's always useful to utilise them. Why reinvent the wheel when there's already a robust implementation that does what you need and more?Gascon
@Gascon Using built in core functions is not reinventing the wheel. People always want to overcomplicate things :STadeas
Lets say down the road after you've finished your project you find that you need to implement timezones in your dates to allow different users to have the correct times. Would you want to go back and recode every time you have a date/time field pop up? I doubt it. date returns a string, there are core functions too allow parsing of the string but why limit yourself in that way in terms of flexibility? Check out the Carbon docs.Gascon
You just set the right timezone in global config and that's it, the same way as carbon works. It's just silly to do things "laravel way", because it looks more fancy? How is this \Carbon\Carbon::now()->format('d.m.Y'); better than date('d.m.Y') ?Tadeas
Thanks So, the date('Y-m-d H:i:s') won't hurt by anyway right ?Glennglenna
@MārtiņšBriedis The Laravel / Carbon way does have its benefits. For example if you want to use their useful wrapper functions to manipulate date objects you can easily do this with very readable code and it also handles timezone issues and other tedious date formatting. If its part of the framework then its always good to use the abstractions.Revolution
M
71

Php has a date function which works very well. With laravel and blade you can use this without ugly <?php echo tags. For example, I use the following in a .blade.php file...

Copyright © {{ date('Y') }}

... and Laravel/blade translates that to the current year. If you want date time and day, you'll use something like this:

{{ date('Y-m-d H:i:s') }}
Mattoid answered 19/2, 2017 at 7:28 Comment(0)
S
25

If you want to use datetime class do:

$dt = new DateTime();
echo $dt->format('Y-m-d H:i:s');

The documentation for reference.

Strikebound answered 23/1, 2015 at 11:51 Comment(0)
C
19

From Laravel 5.5 you can use now() function to get the current date and time.

In blade file, you can write like this to print date.

{{  now()->toDateTimeString('Y-m-d') }}

enter image description here

For more information check doc

Cherianne answered 20/3, 2019 at 10:14 Comment(0)
E
10

Here is another way to do this

Use \Carbon\Carbon;

$date = Carbon::now();

echo $date->toRfc850String();

Output will be like this

Saturday, 11-May-19 06:28:04 UTC
Edify answered 11/5, 2019 at 6:28 Comment(0)
F
8

How about

    $date = Carbon::now();
    return $date->toArray();

will give you

{
  "year": 2019,
  "month": 1,
  "day": 27,
  "dayOfWeek": 0,
  "dayOfYear": 26,
  "hour": 10,
  "minute": 28,
  "second": 55,
  "englishDayOfWeek": "Sunday",
  "micro": 967721,
  "timestamp": 1548570535,
  "formatted": "2019-01-27 10:28:55",
  "timezone": {
    "timezone_type": 3,
    "timezone": "Asia/Dubai"
  }
}

The same props are accessible through


    return [
             'date' => $date->format('Y-m-d'),
              'year' => $date->year,
              'month' => $date->month,
              'day' => $date->day,
              'hour' => $date->hour,
              'isSaturday' => $date->isSaturday(),
          ];

Frederickafredericks answered 27/1, 2019 at 6:34 Comment(0)
W
5

FOR LARAVEL 5.x

I think you were looking for this

$errorLog->timestamps = false;
$errorLog->created_at = date("Y-m-d H:i:s");
Warmongering answered 11/1, 2018 at 11:55 Comment(0)
R
4

You can try this.

use Carbon\Carbon;

$date = Carbon::now()->toDateTimeString();
Rosenblast answered 14/12, 2018 at 4:53 Comment(0)
R
4

I prefer to use a built-in PHP function. if you want to get timestamp format such as "2021-03-31" you can write code like this

$date = date('Y-m-d', time());

for the time you can write like this

$date = date('H:i:s', time());

for the day you can write like this

$date = date('l', time()); // lowercase of L

function time() will give you the current UNIX time and you convert it to whatever format you need.

So, you don't need any third-party package anymore :)

You can read more about UNIX time in this Wikipedia page and convert it in this webiste

Last, for the formatting, you can visit the w3schools page.

Ramp answered 31/3, 2021 at 14:36 Comment(0)
I
4

I use now() on laravel 8 to create a user

User::create([
   'name'=>'admin',
   'email'=>'[email protected]',
   'email_verified_at'=>now(),
   'password'=>bcrypt('123456'),
]);
If answered 22/12, 2021 at 7:46 Comment(0)
O
3

data

return now()->toDateString();

Time

return now()->toTimeString(); 
Oliveira answered 1/3, 2022 at 21:41 Comment(1)
now()->getTimestamp() also workingHerminahermine
K
2

You have a couple of helpers.

The helper now() https://laravel.com/docs/7.x/helpers#method-now

The helper now() has an optional argument, the timezone. So you can use now:

now();

or

now("Europe/Rome");

In the same way you could use the helper today() https://laravel.com/docs/7.x/helpers#method-today. This is the "same thing" of now() but with no hours, minutes, seconds.

At the end, under the hood they use Carbon as well.

Kitkitchen answered 16/5, 2020 at 6:35 Comment(0)
E
2

Try this,

$tmp = (new DateTime)->format('d-m-Y');
echo $tmp;

to Timestamp.

$kTsp = (new DateTime)->getTimestamp();
echo $kTsp;
Elveraelves answered 27/5, 2022 at 14:29 Comment(0)
B
1
use DateTime;

$now = new DateTime();
Bricklaying answered 14/9, 2017 at 21:36 Comment(0)
A
1

It's very simple:

Carbon::now()->toDateString()

This will give you a perfectly formatted date string such as 2020-10-29.

In Laravel 5.5 and above you can use now() as a global helper instead of Carbon::now(), like this:

now()->toDateString()
Adventuresome answered 29/10, 2020 at 5:10 Comment(0)
D
1

Laravel Blade View:

{{\Carbon\Carbon::now()->format('d-m-Y')}}

With timezone:

{{\Carbon\Carbon::now("Asia/Tokyo")->format('d-m-Y')}}

Format available list: https://www.php.net/manual/en/datetime.format.php

Timezone available list: https://www.php.net/manual/en/timezones.php

Devastate answered 20/5, 2021 at 9:26 Comment(0)
M
1

If you need the date directly in a input value of your view this can help you: (myview .blade.php)

<input type="date" name="Date" value="{{date('Y-m-d', time())}}">
Mimosa answered 23/9, 2021 at 23:32 Comment(0)
P
0
//vanilla php
Class Date {
    public static function date_added($time){
         date_default_timezone_set('Africa/Lagos');//or choose your location
        return date('l F Y g:i:s ',$time);

    }


}
Prompter answered 11/9, 2016 at 20:57 Comment(0)
V
0

You can set the timezone on you AppServicesProvider in Provider Folder

public function boot()
{
    Schema::defaultStringLength(191);
    date_default_timezone_set('Africa/Lagos');
}

and then use Import Carbon\Carbon and simply use Carbon::now() //To get the current time, if you need to format it check out their documentation for more options based on your preferences enter link description here

Valse answered 15/6, 2018 at 13:31 Comment(0)
B
-1

You can use today() function.

$today = today('Europe/London');
$dayOfYear = $today->dayOfYear;
$dayOfWeek = $today->dayOfWeek;
Bull answered 13/3, 2020 at 6:50 Comment(0)
O
-1

today data and time

return now::();

time

return now()->toTimeString();
Oliveira answered 12/2, 2022 at 23:4 Comment(1)
Hi ali, with 21 other answers already present, it would be great if you could add an explanation to your code to help us understand how it is different from other answers and how it solves the problem in the way that other answers dont. Thanks!Radiator

© 2022 - 2024 — McMap. All rights reserved.