LoginSignup
26
21

More than 5 years have passed since last update.

PHPのDataTimeを使って月初と月終を出すだけ

Last updated at Posted at 2016-02-25

strtotimeを使ったやつばっかり見つかる。
多分ちょっと考えればいいけどすぐ忘れちゃうのでメモ代わり。
注意:時間は現在の時間がとれてしまうので、必要だったら指定してあげてください。

1.今月の月初、月終とか出すとき

date.php
<?php
    //月初め
    $startDate = new DateTime('first day of this month');
    //月終わり
    $endDate  = new DateTime('last day of this month');
    //出力
    echo $startDate->format('Y-m-d');
    echo $endDate->format('Y-m-d');
?>

来月出すなら「this month」を「next month」を変えるとかでいけます。
先月出すなら「this month」を「last month」を変えるとかでいけます。

相対的にとるやつすごくわかりやすいのでつかっていきたい。

2.先月の月初、月終とか出すとき(失敗)

やってはいけないやつ。

date.php
<?php
    //月初め
    $startDate = new DateTime('first day of -1 month');
    //月終わり
    $endDate  = new DateTime('last day of -1 month');
    //出力
    echo $startDate->format('Y-m-d');
    echo $endDate->format('Y-m-d');
?>

一見うまくいくのですが、5月31日とかに動かしたりすると5月の末日をとって4月32日になることもある。
ーーーーそして5月1日へ…

3.指定の月の月初め、月終とか出すとき

date.php
<?php
    //指定の年月
    $Month = '2016-02';
    //月初め
    $startDate = new DateTime('first day of ' . $Month);
    //月終わり
    $endDate  = new DateTime('last day of ' . $Month);
    //出力
    echo $startDate->format('Y-m-d');
    echo $endDate->format('Y-m-d');
?>

YYYYMM形式でうまくいかないかなーって思ったけどうまくいかないので気をつけてあげてください。
と言ったが嘘だった。自分の頭悪いだけだった。申し訳ない。

4.好きなフォーマットで指定の月の月初め、月終とか出すとき

date.php
<?php
    //指定の年月
    $Month = '201602';
    // 好きなフォーマット
    $format = 'Ymd';
    // 集計テーブルに入れる年月 何も指定しないと現在の年月日時が入ってしまい31日とかに動かすと31日がない月を指定した時に死んでしまいます。(次の月になってしまいます)
    $month = DateTime::createFromFormat($format, $Month . '01');
    //月初め
    $startDate = new DateTime('first day of ' . $month->format('Y-m'));
    //月終わり
    $endDate  = new DateTime('last day of ' . $month->format('Y-m'));
    //出力
    echo $startDate->format('Y-m-d');
    echo $endDate->format('Y-m-d');
?>

好きなフォーマットで集計できる!!!!!!!!!!しあわせ!!!!!

26
21
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
26
21