2016年6月2日 星期四

strtotime做日期及時間加減計算-[php]

strtotime做日期及時間加減計算-[php] 

範例1:
$today = '2016-06-02';
//年
echo date("Y-m-d", strtotime($today."+3 year"));
//月
echo date("Y-m-d", strtotime($today."-1 month"));
//週
echo date("Y-m-d", strtotime($today."+10 week"));
//日
echo date("Y-m-d", strtotime($today."+10 day"));
//時
echo date("Y-m-d", strtotime($today."+2 hour"));
//分
echo date("Y-m-d", strtotime($today."+20 minute"));
//秒
echo date("Y-m-d", strtotime($today."+5 seconds"));
範例2:
//加1天5秒
echo date("Y-m-d", strtotime($today."+1 day 5 seconds"));
//加1週減2天
echo date("Y-m-d", strtotime($today."+1 week -2 day"));
範例3:
echo date( "Y-m-d", strtotime( "2016-01-31 +1 month" ) );  // PHP:  2016-03-02
echo date( "Y-m-d", strtotime( "2016-01-31 +2 month" ) );  // PHP:  2009-03-31
 // MySQL:  2016-02-28
SELECT DATE_ADD( '2016-01-31', INTERVAL 1 MONTH );
注意事項:
若只有指定日期而未指定時間,默認日期當天00:00:00為時間。

Reference: 
1. PHP官方 - strtotime
http://php.net/manual/en/function.strtotime.php


沒有留言: