4
4

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 1 year has passed since last update.

CarbonPeriodって?

使いどころ

20XX年X月度日別アクセス数の集計するときとか…
年代別にユーザーを取得するときとか…
要するに特定の期間を指定した間隔で取り出して配列でゴニョゴニョしたいとき

前提条件

  • Carbonのversionが1.29以降

個人的によく利用する方法

  • 秒単位
$period = CarbonPeriod::create('2021-12-01 00:00:00', '2021-12-01 00:01:00')->seconds()->toArray();

// 2021-12-01 00:00:00, 2021-12-01 00:00:01, 2021-12-01 00:00:02…
  • 分単位
$period = CarbonPeriod::create('2021-12-01 00:00:00', '2021-12-01 00:30:00')->minutes()->toArray();

// 2021-12-01 00:00:00, 2021-12-01 00:01:00, 2021-12-01 00:02:00…
  • 時間単位
$period = CarbonPeriod::create('2021-12-01 00:00:00', '2021-12-01 23:59:59')->hours()->toArray();

// 2021-12-01 00:00:00, 2021-12-01 01:00:00, 2021-12-01 02:00:00…
  • 1日単位
$period = CarbonPeriod::create('2021-12-01', '2021-12-31')->toArray();

// 2021-12-01 00:00:00, 2021-12-02 00:00:00, 2021-12-03 00:00:00…
  • 週単位
$period = CarbonPeriod::create('2021-12-01', '2021-12-31')->weeks()->toArray();

// 2021-12-01 00:00:00, 2021-12-08 00:00:00, 2021-12-15 00:00:00…
  • 月単位
$period = CarbonPeriod::create('2021-01-01', '2021-12-31')->months()->toArray();

// 2021-01-01 00:00:00, 2021-02-01 00:00:00, 2021-03-01 00:00:00…
  • 年単位
$period = CarbonPeriod::create('2019-02-01', '2021-12-31')->years()->toArray();

// 2019-02-01 00:00:00, 2020-02-01 00:00:00, 2021-02-01 00:00:00…
  • 〇日おき
$period = CarbonPeriod::since('2021-12-01')->days(3)->until('2021-12-31')->toArray();
$period = CarbonPeriod::create('2021-12-01', '3 days', '2021-12-31')->toArray();

// 2021-12-01 00:00:00, 2021-12-04 00:00:00, 2021-12-07 00:00:00…
  • 特定の日から今日まで or 今日から特定の日まで
$period = CarbonPeriod::start('2021-12-13')->untilNow()->toArray();

// 2021-12-13 00:00:00, 2021-12-14 00:00:00, 2021-12-15 00:00:00…

$period = CarbonPeriod::untilNow()->end('2021-12-31')->toArray();

// 2021-12-15 00:00:00, 2021-12-16 00:00:00, 2021-12-17 00:00:00…

おまけ

  • 期間の最初と最後
$period = CarbonPeriod::create('2020-01-01', '2021-12-31')->first();

// 2020-01-01 00:00:00

$period = CarbonPeriod::create('2020-01-01', '2021-12-31')->last();

// 2021-12-31 00:00:00
  • 逆にして取り出す
$period = array_reverse(CarbonPeriod::create('2021-12-01', '2021-12-31')->toArray());

// 2021-12-31, 2021-12-30, 2021-12-29, 2021-12-28, 2021-12-27…

以上

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?