2010年3月8日月曜日

PHP 日付の計算(加算、減算)

PHPでの日付の計算(加算、減算)でーす。
使うのはこちら↓↓

strtotime関数
int strtotime ( string 英文字の日時 [, int 日付])
※「int 日付」は初期値がnow(現在)

これを使うと日、週、月、年の加算、減算が簡単に計算できます。
時・分・秒の加算、減算もできます。

「英文字の日時」の部分は加算、減算したい単位を設定。
day、week、month、year、hour、minute、second等。
ちなみに now は現在の時間です。

使い方はこんな感じ。

print "昨日:" . date("Y/m/d",strtotime("-1 day" ,strtotime(now))) . "<BR>";

print "今日:" . date("Y/m/d",strtotime("now")) . "<BR>";

print "明日:" . date("Y/m/d",strtotime("1 day")) . "<BR>";

print "明日:" . date("Y/m/d",strtotime("1 day" ,strtotime(now))) . "<BR>";

print "1週間後:" . date("Y/m/d",strtotime("1 week" ,strtotime(now))) . "<BR>";

print "1月後:" . date("Y/m/d",strtotime("1 month" ,strtotime(now))) . "<BR>";

print "1年後:" . date("Y/m/d",strtotime("1 year" ,strtotime(now))) . "<BR>";

print "指定した日付の1月前:" . date("Y/m/d",strtotime("-1 month" ,strtotime("2010/3/20"))) . "<BR>";

print "年月日時分秒:" . date("Y/m/d H:i:s",strtotime(now)) . "<BR>";

print "1時間後:" . date("Y/m/d H:i:s",strtotime("1 hour" ,strtotime(now))) . "<BR>";


結果はこうなります。

昨日:2010/03/07
今日:2010/03/08
明日:2010/03/09
明日:2010/03/09
1週間後:2010/03/15
1月後:2010/04/08
1年後:2011/03/08
指定した日付の1月前:2010/02/20
年月日時分秒:2010/03/08 23:36:39
1時間後:2010/03/09 00:36:39

ただ、残念な事に月の計算ではうまくいかない事があります。

print "指定した日付の1月前:" . date("Y/m/d",strtotime("-1 month" ,strtotime("2010/3/31")));

この場合結果が

指定した日付の1月前:2010/03/03

となってしまいます。
どうも2月31日がないので、「2月28日+3日=3月3日」という感じのようです。この点は注意が必要ですね。

0 件のコメント:

コメントを投稿