こんなコードを書いてみました。
(質問ようにコンパクトにしてしまったために再現しなくなっていたので、元のコードに差し替えました。)
php
1// 1月前の日付を得る 2$now = new DateTime(); 3$begin_date = $now; 4$begin_date->sub(new DateInterval('P1M')); 5echo $begin_date->format('Ymd'); 6// 1日前の日付を得る 7$end_date = $now; 8$end_date->sub(new DateInterval('P1D')); 9echo $end_date->format('Ymd');
今日は2017年3月1日なので、end_dateは「20170228」という出力が得られるものと期待しましたが、「20170131」が得られました。
DateTimeクラスやDateIntervalクラスって本当に大丈夫なんでしょうか。
もしかして、$nowも$begin_dateも$end_dateも繋がっちゃってますかね。
結果的に、下記のブログ記事を見つけて対応したので問題なしですが、少し気味が悪いです。
(テスト環境は、XAMPP-Windowsに含まれているPHP 5.4.16)
前日日付などを取得する方法 - Chocotte de Choo
php
1date("Ymd",strtotime("-1 day")); //1日前 2date("Ymd",strtotime("-1 week")); //1週間前 3date("Ymd",strtotime("-1 month")); //1月前 4date("Ymd",strtotime("-1 year")); //1年前 5date("Ymd",strtotime("1 day")); //1日後 6date("Ymd",strtotime("1 week")); //1週間後 7date("Ymd",strtotime("1 month")); //1月後 8date("Ymd",strtotime("1 year")); //1年後
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/03/01 11:14
2017/03/01 11:20
退会済みユーザー
2017/03/01 11:24
2017/03/01 11:25
退会済みユーザー
2017/03/01 11:28
2017/03/01 11:28
2017/03/01 11:29
退会済みユーザー
2017/03/01 11:31
2017/03/01 11:39
2017/03/01 11:50
退会済みユーザー
2017/03/01 11:58
2017/03/01 12:01