Skip to content

Instantly share code, notes, and snippets.

@sola-msr
Last active November 13, 2018 09:27
Show Gist options
  • Save sola-msr/41c686eb2c746a0e275fa8489613a4f6 to your computer and use it in GitHub Desktop.
Save sola-msr/41c686eb2c746a0e275fa8489613a4f6 to your computer and use it in GitHub Desktop.
【PHP】ある月の初日と末日を取得する方法(DateTimeクラス & Carbon編) ref: https://qiita.com/sola-msr/items/58479913ff62452b6bb6
date_default_timezone_set('Asia/Tokyo');
$setYear = 2018;
$setMonth = 2;
$date = new DateTime();
$month['first_day'] = $date->setDate($setYear, $setMonth, 1)->format('Y-m-d'); // 日を1で固定値を入れている
$month['last_day'] = $date->setDate($setYear, $setMonth, 1)->format('Y-m-t'); // 日を1で固定値を入れている
var_dump($month);
/* 実行結果
array(2) {
["first_day"]=>
string(10) "2018-02-01"
["last_day"]=>
string(10) "2018-02-28"
}
*/
$setYear = 2018;
$setMonth = 2;
$month['first_day'] = Carbon::create($setYear, $setMonth, 1)->firstOfMonth(); // 日を1で固定値を入れている
$month['last_day'] = Carbon::create($setYear, $setMonth, 1)->lastOfMonth(); // 日を1で固定値を入れている
var_dump($month);
/* 実行結果
array(2) {
["first_day"]=>
string(10) "2018-02-01"
["last_day"]=>
string(10) "2018-02-28"
}
*/
Psy Shell v0.9.6 (PHP 7.2.5-1+ubuntu18.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> use Carbon\Carbon;
>>> Carbon::create(2018, 1)->lastOfMonth();
=> Carbon\Carbon @1517356800 {#2846
date: 2018-01-31 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 2)->lastOfMonth();
=> Carbon\Carbon @1522454400 {#2839
date: 2018-03-31 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 3)->lastOfMonth();
=> Carbon\Carbon @1522454400 {#2844
date: 2018-03-31 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 6)->lastOfMonth();
=> Carbon\Carbon @1530316800 {#2847
date: 2018-06-30 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 2)->daysInMonth;
=> 31
>>>
Psy Shell v0.9.6 (PHP 7.2.5-1+ubuntu18.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> use Carbon\Carbon;
>>> Carbon::create(2018, 1)->lastOfMonth();
=> Carbon\Carbon @1517356800 {#2846
date: 2018-01-31 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 2)->lastOfMonth();
=> Carbon\Carbon @1519776000 {#2839
date: 2018-02-28 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 3)->lastOfMonth();
=> Carbon\Carbon @1522454400 {#2844
date: 2018-03-31 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 6)->lastOfMonth();
=> Carbon\Carbon @1530316800 {#2847
date: 2018-06-30 00:00:00.0 UTC (+00:00),
}
>>> Carbon::create(2018, 2)->daysInMonth;
=> 28
>>>
2018-02-28 + 1 = 2018-03-01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment