LoginSignup
21
16

More than 5 years have passed since last update.

PHPで確実に来月末や来月1日を求める

Last updated at Posted at 2017-01-30

来月1日を求める場合、こんなコードを書いてたんだけど、これを1月30日に実行すると、2月30日がないので、繰り越して3月になってしまう。

// Today = 2017-01-30
date('Y-m-01', strtotime(date('+1 month')) // 2017-03-01

ほしいのは2月1日なので、今月1日から計算をする。

// Today = 2017-01-30
date('Y-m-01', strtotime(date('Y-m-01').'+1 month')) // 2017-02-01

追記(2017.02.05)

こんな書き方もあるようです。

// Today = 2017-01-30
date('Y-m-d', strtotime('first day of next month', strtotime(date('Y-m-d')))) // 2017-02-01
// Today = 2017-01-30
date('Y-m-01', mktime(0, 0, 0, date('n') + 1, 1, date('Y'))) // 2017-02-01

修正(2017.09.19)

mktime()を使った方法を修正しました。

// Today = 2017-09-19

// 誤:日付が0になってるので、今月初日を返してしまう
date('Y-m-01', mktime(0, 0, 0, date('n') + 1, 0, date('Y'))) // 2017-09-01

// 正
date('Y-m-01', mktime(0, 0, 0, date('n') + 1, 1, date('Y'))) // 2017-10-01
21
16
5

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