所有开发人员都有一个工具箱,其中包含他们沿途选择或编写的有用函数和类,当我为客户编写活动日历页面时,我想到了这个 PHP。
我应该提一下,PHP 确实为 PHP 4.0.7 及更高版本的 PHP 构建提供了一个 cal_days_in_month 函数,但我更喜欢使用下面的函数,因为它保证可以在所有 PHP 版本上工作,因为它完全基于逻辑。
代码
function get_days_in_month($month, $year) { return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31); }
一行逻辑提供一个月中的天数,考虑到闰年,并且全部在一行上。