LoginSignup
1
1

More than 5 years have passed since last update.

DateTimeオブジェクトで正確に次月を求める

Posted at

phpで以下のようにDateTimeを使って年月一覧を出力するみたいなことしてたんですが

<ul>
<?php for ($i = 0, $date = new DateTime(); $i < 12; $i++, $date->add(new DateInterval('P1M'))): ?>
<li><?php echo $date->format('Y/m') ?></li>
<?php endfor; ?>
</ul>

これだと、本日5月31日のような日は、31日分追加されて6月越して7月になってしまいましたん。

$date = new DateTime();
echo $date->format('Y/m/d'); // 2018/05/31
$date->add(new DateInterval('P1M'));
echo $date->format('Y/m/d'); // 2018/07/01

modify使うと、正確に次月に得られました

$date = new DateTime();
echo $date->format('Y/m/d'); // 2018/05/31
$date->modify('first day of next month');
echo $date->format('Y/m/d'); // 2018/06/01

こわいこわい

<ul>
<?php for ($i = 0, $date = new DateTime(); $i < 12; $i++, $date->modify('first day of next month')): ?>
<li><?php echo $date->format('Y/m') ?></li>
<?php endfor; ?>
</ul>
1
1
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
1
1