LoginSignup
8

More than 5 years have passed since last update.

指定範囲の月日 (YYYYMM) のリストを作る関数

Last updated at Posted at 2015-01-14

こーど

これ以上にスマートな書き方あるかしら。(反語)

function getMonthRange($startUnixTime, $endUnixTime = null) {
    if ($endUnixTime === null) {
        $endUnixTime = time();
    }
    $ymList = array();
    for ($utime = $startUnixTime; $utime <= $endUnixTime; $utime = strtotime('+1 month', $utime)) {
        $ymList[] = date('Ym', $utime);
    }
    return $ymList;
}

ざつだん

いつでもプログラム書く上での日付のインクリメント/デクリメントが地味にハマりポイント

月を増減するのに $nextMonth = time() + (86400 * 30) ってするとうまくいかないパターンがあるのはわかっても、 $nextDay = time() + 86400 が (いちおう厳密には) 正確じゃないっていう。うるう秒的に。

結局はPHP大先生のstrtotimeという痒いところに手が届くステキ機能のお力を借りて、+1 month なり、 +1 day なりするのが一番いいのかしらねぇ。

大昔に自分が書いたPerlとか見ると $month++ して $month>12 だったら $year++ したうえで $month=1するようなバグインキュベーターコードが見えるのでPHP先生はすばらしい!さすが!

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
8