简体   繁体   中英

Laravel - format date from Mysql database with carbon

In my Laravel project I have a MySQL database table with the following column:

 |   requested_at  |
 2018-02-03 12:00:00
 2018-03-03 11:00:00

I want to get all items from this column where the timestamp (requested_at) is older than 60 days:

$now = Carbon::now ();  

$60days  = DB::table('exampletable')->where('requested_at', '=', $now->subDays(60))->get();

For my following code I need to format the Date format from my column requested at .

I only want to get the date like this 2018-03-03 without the time.

I play around with some carbon methods but It didn't work at all:

$format60 = Carbon::createFromFormat('Y-m-d', $60days);

You can achieve this by mysql only, no need of carbon.
Just using datediff() and now() of mysql.
Do like this

$days60  = DB::table('exampletable')
    ->whereRaw('datediff(now(),requested_at) = 60')
    ->get();

Example :- 在此处输入图片说明

It seems that you are using TIMESTAMP type so

->where('requested_at', '<=', now()->subDays(60)->startOfDay())->get();

As you can see there is no need to format Carbon instance.

Break it all down:

now() // Laravel helper to get Carbon::now()
->subDays(60) // subtract 60 days
->startOfDay() // set time part of timestamp to start of the day

Note : add requested_at into $dates array in your model for easier use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM