LoginSignup
0
0

More than 5 years have passed since last update.

[PHP]日付ライブラリ「Carbon」の挙動を確認する※随時更新

Posted at

概要

  • 現在のプロジェクトでPHPの日付ライブラリである「Carbon」使用している
  • 自分にとって一部挙動がよく分からない箇所があるのでテストコードを書いて確認する
  • ドキュメントを読んでいるが実際に確認したほうが安心というのもある
  • 確認したものから随時更新していく
  • 確認はメソッド単位で行う

diffInMonths()

  • Carbonインスタンス同士を比較して「経過した月数」を返すメソッド
/**
 * Test diffInMonths()
 */
public function testDiffInMonths()
{
    // 現在日時同士
    $carbon1 = Carbon::now();
    $carbon2 = Carbon::now();
    $this->assertEquals(0, $carbon1->diffInMonths($carbon2));

    // 1ヶ月経過してない
    $carbon1 = Carbon::createFromFormat('Y-m-d', '2016-02-01');
    $carbon2 = Carbon::createFromFormat('Y-m-d', '2016-02-01')->addMonth()->subDay();
    $this->assertEquals(0, $carbon1->diffInMonths($carbon2)); // true

    // 1ヶ月経過した
    $carbon1 = Carbon::createFromFormat('Y-m-d', '2016-02-01');
    $carbon2 = Carbon::createFromFormat('Y-m-d', '2016-02-01')->addMonth();
    $this->assertEquals(1, $carbon1->diffInMonths($carbon2)); // true

    // 2ヶ月経過した
    $carbon1 = Carbon::createFromFormat('Y-m-d', '2016-02-01');
    $carbon2 = Carbon::createFromFormat('Y-m-d', '2016-02-01')->addMonths(2);
    $this->assertEquals(2, $carbon1->diffInMonths($carbon2)); // true

    // 1年1ヶ月経過した
    $carbon1 = Carbon::createFromFormat('Y-m-d', '2016-02-01');
    $carbon2 = Carbon::createFromFormat('Y-m-d', '2016-02-01')->addYear()->addMonth();
    $this->assertEquals(13, $carbon1->diffInMonths($carbon2)); // true
}
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