0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Carbonで次の特定曜日の日付を取得する方法

Last updated at Posted at 2021-10-14

最近Carbonのnext/previousを見つけてテストコードや曜日に関連した処理を作るときにに便利そうだったのでメモです!

特定の日付から次の〇曜日を取得する

$today = Carbon::parse('2021/10/14');
// 2021/10/18(Mon)
dump($today->copy()->next(Carbon::MONDAY)->format('Y/m/d(D)'));
// 2021/10/19(Tue)
dump($today->copy()->next(Carbon::TUESDAY)->format('Y/m/d(D)'));
// 2021/10/20(Wed)
dump($today->copy()->next(Carbon::WEDNESDAY)->format('Y/m/d(D)'));
// 2021/10/21(Thu)
dump($today->copy()->next(Carbon::THURSDAY)->format('Y/m/d(D)'));
// 2021/10/15(Fri)
dump($today->copy()->next(Carbon::FRIDAY)->format('Y/m/d(D)'));
// 2021/10/16(Sat)
dump($today->copy()->next(Carbon::SATURDAY)->format('Y/m/d(D)'));
// 2021/10/17(Sun)
dd($today->copy()->next(Carbon::SUNDAY)->format('Y/m/d(D)'));

特定の日付から前の〇曜日を取得する

$today = Carbon::parse('2021/10/14');
// 2021/10/11(Mon)
dump($today->copy()->previous(Carbon::MONDAY)->format('Y/m/d(D)'));
// 2021/10/12(Tue)
dump($today->copy()->previous(Carbon::TUESDAY)->format('Y/m/d(D)'));
// 2021/10/13(Wed)
dump($today->copy()->previous(Carbon::WEDNESDAY)->format('Y/m/d(D)'));
// 2021/10/07(Thu)
dump($today->copy()->previous(Carbon::THURSDAY)->format('Y/m/d(D)'));
// 2021/10/08(Fri)
dump($today->copy()->previous(Carbon::FRIDAY)->format('Y/m/d(D)'));
// 2021/10/09(Sat)
dump($today->copy()->previous(Carbon::SATURDAY)->format('Y/m/d(D)'));
// 2021/10/10(Sun)
dd($today->copy()->previous(Carbon::SUNDAY)->format('Y/m/d(D)'));

Carbon便利ですね😊

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?