【php】日付算出(1日前、2日前…1ヶ月前、1年前 etc.)
2010/02/15
php
現在からの相対日付を求める計算例phpスクリプト
<?php $x = array(); //現在 $x[] = "現在 " . date("Y-m-d H:i:s"); //現在からの相対日付(前) $x[] = "1日前 " . date("Y-m-d H:i:s",strtotime("-1 day")); $x[] = "1ヶ月前 " . date("Y-m-d H:i:s",strtotime("-1 month")); $x[] = "1年前 " . date("Y-m-d H:i:s",strtotime("-1 year")); $x[] = "1週間前 " . date("Y-m-d H:i:s",strtotime("-1 week")); $x[] = "1時間前 " . date("Y-m-d H:i:s",strtotime("-1 hour")); $x[] = "1分前 " . date("Y-m-d H:i:s",strtotime("-1 minute")); $x[] = "1秒前 " . date("Y-m-d H:i:s",strtotime("-1 second")); //現在からの相対日付(後) $x[] = "1日後 " . date("Y-m-d H:i:s",strtotime("+1 day")); $x[] = "1ヶ月後 " . date("Y-m-d H:i:s",strtotime("+1 month")); $x[] = "1年後 " . date("Y-m-d H:i:s",strtotime("+1 year")); $x[] = "1週間後 " . date("Y-m-d H:i:s",strtotime("+1 week")); $x[] = "1時間後 " . date("Y-m-d H:i:s",strtotime("+1 hour")); $x[] = "1分後 " . date("Y-m-d H:i:s",strtotime("+1 minute")); $x[] = "1秒後 " . date("Y-m-d H:i:s",strtotime("+1 second")); //結果 var_export($x);
結果
array ( 0 => '現在 2010-02-23 22:16:58', 1 => '1日前 2010-02-22 22:16:58', 2 => '1ヶ月前 2010-01-23 22:16:58', 3 => '1年前 2009-02-23 22:16:58', 4 => '1週間前 2010-02-16 22:16:58', 5 => '1時間前 2010-02-23 21:16:58', 6 => '1分前 2010-02-23 22:15:58', 7 => '1秒前 2010-02-23 22:16:57', 8 => '1日後 2010-02-24 22:16:58', 9 => '1ヶ月後 2010-03-23 22:16:58', 10 => '1年後 2011-02-23 22:16:58', 11 => '1週間後 2010-03-02 22:16:58', 12 => '1時間後 2010-02-23 23:16:58', 13 => '1分後 2010-02-23 22:17:58', 14 => '1秒後 2010-02-23 22:16:59', )
3/31から1カ月前とかだと正しく動作しないらしいですよ。
http://d.hatena.ne.jp/bushimichi/20091101/1257007448
コメントありがとうございます。こんな感じですね。
$ /usr/bin/php -r "echo date('Y-m-d H:i:s', strtotime('2010-03-31 -1 month'));"
→ 2010-03-03 00:00:00
正しいんでしょうけど、期待した結果ではないですよね。なので、あまり業務で使う機会はなかったりします。
https://tech.softel.co.jp/blog/archives/1438
schtasksでDAILYのときに、時刻を指定したい | 料理好き男 貯金と家計簿 2015年1月17日 15:36
[…] $x[] = "1時間前 " . date("Y-m-d H:i:s",strtotime("-1 hour")); $x[] = "1分前 " . date("Y-m-d H:i:s",strtotime("-1 minute")); $x[] = "1秒前 " . date("Y-m-d H:i:s",strtotime("-1 second")); https://tech.softel.co.jp/blog/archives/1401 […]