前日日付などを取得する方法

「今日の日付」
を取得したい場合は、date関数を使って

date("Ymd"); // 年月日
date("Ym"); // 年月
date("d"); // 日

のようにしますが、これとstrtotime関数を使って、前日日付などを取得することが可能です。

date("Ymd",strtotime("-1 day")); //1日前
date("Ymd",strtotime("-1 week")); //1週間前
date("Ymd",strtotime("-1 month")); //1月前
date("Ymd",strtotime("-1 year")); //1年前


date("Ymd",strtotime("1 day")); //1日後
date("Ymd",strtotime("1 week")); //1週間後
date("Ymd",strtotime("1 month")); //1月後
date("Ymd",strtotime("1 year")); //1年後

さすがは
「最も満足度の高いスクリプト言語第一位」
に輝いたPHP。便利な関数がそろっています☆



※2009-03-18追記

date("t", mktime());

で、現在の月の日数が取得できます。
これを応用して、

date("t", mktime(0, 0, 0, $month, 1, $year));

のようにすると、指定した年月の日数が取得できます。

たとえば、一ヶ月前の月(今が三月なので、一月前は「二月」)の日数を求めたい場合、

$preMonth = date("m",strtotime("-1 month"));

で、一月前の月を求めて、

date("t", mktime(0, 0, 0, $preMonth, 1));

とすると、「28」という値が得られます☆



※2009-03-27追記

"1日前" ⇒date("Ymd",strtotime("-1 day" ,strtotime("20090327")));
"1ヶ月前" ⇒date("Ymd",strtotime("-1 month" ,strtotime("20090327")));
"1年前" ⇒date("Y/m/d",strtotime("-1 year",strtotime("20090327")));
"1週間前" ⇒date("Y/m/d",strtotime("-1 week" ,strtotime("20090327")));

「日」も渡さないと、data関数がキチンと働いてくれません(´・ω・`)
※出力する際のフォーマットには「日」は無くてもOK!

$year_month_pre = date("Ym",strtotime("-1 month" ,strtotime($ymd)));
$year_month_next = date("Ym",strtotime("1 month" ,strtotime($ymd)));


※2009-05-12追記

年月日それぞれをバラバラに取得することも可能です。

$nowY = date("Y", strtotime("-1 day"));
$nowM = date("m", strtotime("-1 day"));
$nowD = date("d", strtotime("-1 day"));

2010-02-17追記

現在日時を取得する時の例として(年月日時分秒)、

date("Y-m-d h:i:s");

※「時」を24時間表記にしたければ、hを大文字にする。

date("Y-m-d H:i:s");