1. 程式人生 > >php中,獲取指定日期的當月天數

php中,獲取指定日期的當月天數

在工作中,經常會遇到獲取某一個月份的天數問題,之前我是這麼解決的。

//這裡以2015年11月為例
$inputs['month'] = '201511';//傳遞過來的引數
$tmp_month = $inputs['month']."01";
//$tmp_month = '20151101';
$s_time = strtotime($tmp_month);//月起始時間
$e_time = strtotime(date("Ymd",$s_time).'+1 month');//月結束時間
$countMins = ($e_time - $s_time)/60;//當月分鐘數
$countDay = $countMins
/(60*24);//當月的天數
但是現在,發現了更好的獲取方法。

php內建函式date(),可以直接獲取當月天數。

$tmp_month = $inputs['month']."01";
$countDay = date("t",strtotime($tmp_month));
//如果直接date("t"),得到的是當月的天數

so easy!

其實,還有一個方法,使用cal_days_in_month()函式,php手冊中給的解釋是:返回某個曆法中某年中某月的天數。

3個引數:
calendar 用來計算的某個曆法
month 選定曆法中的某月
year 選定曆法中的某年

$num = cal_days_in_month(CAL_GREGORIAN, 11, 2015); // 30

我個人還是比較喜歡date()函式的,這樣不用考慮曆法的問題。