函數(shù)說(shuō)明
strtotime()
— 將任何字符串的日期時(shí)間描述解析為 Unix 時(shí)間戳
int strtotime ( string $time [, int $now = time() ] )
注意 $time 的日期與時(shí)間格式(見底部參考)
局限
strtotime()
在某些情況下 +1 month
的返回結(jié)果異常.
$test = strtotime('2017-12-31');
echo date('Y-m-d', strtotime('+1 month', $test));
# 期待:2018-01-31
# 輸出:2018-01-31
echo date('Y-m-d', strtotime('+2 month', $test));
# 期待:2018-02-28
# 輸出:2018-03-03
正確的用法
$test = strtotime('2017-12-31');
echo date('Y-m-d', strtotime('last day of +1 month', $test));
# 輸出:2018-01-31
echo date('Y-m-d', strtotime('last day of +2 month', $test));
# 輸出:2018-02-28
在使用 strtotime()
函數(shù)的時(shí)候岳掐,指定每個(gè)月的最后一日,防止 +1 month
「溢出」異常結(jié)果.
last day of 是在某些月份會(huì)「溢出」的時(shí)候加砖织,目的是為了取到該月份的最后一日
不相關(guān)例子
場(chǎng)景
一個(gè)定時(shí)任務(wù)乡洼,每個(gè)月的某天某時(shí)某分觸發(fā)(則當(dāng)前時(shí)間可知)僚纷,求這個(gè)月的最后一天日期.
$ crontab -l
0 0 20 * * /usr/bin/php -f index.php # 每個(gè)月20號(hào) 0:00 執(zhí)行
方法一
$nextMonth = strtotime('+1 month'); // now => 2018-09-19 21:57:59
$nextFirstDay = date('Y-m', $nextMonth) . '-01';
$lastDay = date('Y-m-d', strtotime('-1 day', strtotime($nextFirstDay)));
echo $lastDay;
# 輸出:2018-09-30
方法二
echo date('Y-m-t', time()); // time() => 2018-09-19 21:57:59
# 輸出:2018-09-30
方法三
echo date('Y-m-d', strtotime('last day of this month')); // now => 2018-09-19 21:57:59
# 輸出:2018-09-30
echo date('Y-m-d', strtotime('last day of +0 month')); // now => 2018-09-19 21:57:59
# 輸出:2018-09-30