PHP 的 strtotime() 能把各種英文日期敘述解析成 Unix 時間戳,無論是固定日期、相對時間還是「下週四」這類自然語言,都能輕鬆處理。
<?php
echo strtotime("2006-01-09");
echo strtotime("2006-01-09 08:10");
echo strtotime("now");
echo strtotime("10 September 2000");
echo strtotime("+1 day");
echo strtotime("+1 week");
echo strtotime("+1 week 2 days 4 hours 2 seconds");
echo strtotime("next Thursday");
echo strtotime("last Monday");
?>只要把 strtotime() 的結果交給 date() 格式化,就能做出靈活的日期運算:
今日日期:
$days=date('d',strtotime('now')); //2006-09-06本月月初:
echo $currMBegin=date("Y-m", strtotime('now'))."-01";本月月末:
echo $currMEnd =date("Y-m-d", strtotime("next month -$days day"));下月月初:
echo $nextMBegin=date("Y-m", strtotime('next month'))."-01";下月月底:
echo $nextMEnd =date("Y-m-d", strtotime("+2 months -$days day"));輸出結果會是:
2006-09-01 2006-09-30
2006-10-01 2006-10-31關鍵技巧在於用「下個月再減掉當前天數」的方式,就能精準取得每個月的月末日期。