//找出日期年份是2021年的
->whereYear('datetime', 2021)
//找出日期月份是7月的
->whereMonth('datetime', 7)
//找出小於等於一個月前的 (找出小於等於2021年6月的)
->whereDate('datetime', '<=', (new Carbon("2021-7"))->subMonth(1))
需特別注意,subMonth(x)會改變原來的值,比如以下範例,假如$today是2021/09/24,減掉6個月後$today的值會被更動:
$today = Carbon::today();
$today->subMonth(6) //這時$today=2021/03/24
如果後面繼續$today->subMonth(x),$today會越來越小,這種狀況可以用->toImmutable()來解決,這樣$today就不會變了:
->whereDate('create_datetime', '>=', $today->toImmutable()->subMonth(6))
->whereDate('create_datetime', '>=', $today->toImmutable()->subMonth(1))
//column between two date
->whereBetween('data_create_datetime',
[(new Carbon($start_date))->startOfDay(),
(new Carbon($end_date))->endOfDay()]);
$start_date = 2021/10/13
$end_date = 2021/10/20
(new Carbon($start_date))->startOfDay() // => 2021/10/13 00:00:00
(new Carbon($end_date))->endOfDay() // => 2021/10/20 23:59:59
//date between two columns
->whereDate('start_datetime', '<=', $date)->whereDate('end_datetime', '>=', $date)
//日期format轉換
Carbon::parse("2021/11/28")->format('Y-m-d'); //2021-11-28
//減1小時
Carbon::parse("2021-12-03 16:00:00")->subHour(1); //2021-12-03 15:00:00
//現在時間與指定時間差了幾分鐘
$diff_in_minutes = (Carbon::now())->diffInMinutes('09:00:00', false);
帶入false表示回傳的相減分差會有正負數,如果帶true,則都會是正數。