计算一个月的天数函数
All developers keep a tool box of useful functions and classes that they pick up or write along the way and this PHP came to me while I was writing an event calendar page for a customer.
所有开发人员都保留了一个包含有用功能和类的工具箱,他们会沿用或编写这些有用的函数和类,而当我为客户编写事件日历页面时,这个PHP来了。
I should mention that PHP does offer a cal_days_in_month function for PHP builds of PHP 4.0.7 and higher, but I prefer using the below function because it is guaranteed to work on all PHP version because it is based solely on logic.
我应该提到,PHP确实为PHP 4.0.7及更高版本PHP版本提供了一个cal_days_in_month函数,但是我更喜欢使用以下函数,因为它可以在所有PHP版本上使用,因为它完全基于逻辑。
代码 (The Code)
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);
}
One line of logic provides the number of days in a month, taking into account leap years, and all on one line.
一条逻辑线考虑了leap年,提供了一个月中的天数,并且全部在一条线上。
翻译自: https://davidwalsh.name/php-function-calculating-days-in-a-month
计算一个月的天数函数