如何计算一个月中的工作日数?
我现在遇到这个问题:给定一个月和一年,我需要知道它有多少个工作日(即,不包括周六和周日的天数)。
看起来很简单,但我却感到困惑。当然,我可以用 for 循环来解决它,并检查这一天是星期六还是星期日,如果不是则增加计数器,但这只是简单的愚蠢(和线性时间),考虑到我很确定我可以通过几个除法或模数来逃脱。
对算法有什么想法吗?您可以使用 PHP 4.4.1 的所有功能。
编辑这是一个有效的for
循环实现:
function weekdays_in_month($month, $year)
{
$days_in_month = days_in_month($month); // days_in_month defined somewhere
$first_day = date('w', mktime(0,0,0, $month, 1, $year));
$counter = 0;
for ($i = 0; $i < $days_in_month; $i++)
{
if (($first_day + $i + 1) % 7 >= 2)
$counter++;
}
return $counter;
}
I'm having this problem right now: given a month and a year, I'd need to know how many week days it has (that is, the number of days excluding Saturday and Sunday).
It seems so simple, and yet I'm baffled. Of course I could solve it with a for
loop and check if the day's a Saturday or a Sunday, and if not increment a counter, but this is just plain stupid (and linear time) considering I'm pretty sure I could get away with a couple of divisions or modulos.
Any idea of the algorithm? You have all the power of PHP 4.4.1 at your disposal.
EDIT Here's a working for
loop implementation:
function weekdays_in_month($month, $year)
{
$days_in_month = days_in_month($month); // days_in_month defined somewhere
$first_day = date('w', mktime(0,0,0, $month, 1, $year));
$counter = 0;
for ($i = 0; $i < $days_in_month; $i++)
{
if (($first_day + $i + 1) % 7 >= 2)
$counter++;
}
return $counter;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需检查 29 日、30 日和 31 日是工作日(如果这些日期存在)。
添加 20.
编辑您的函数:
Just check the weekday-ness of the 29th, 30th, and 31st (if these dates exist).
Add 20.
Editing your function:
您可以搜索一年中的第一个和最后一个星期日,然后将这两个日期的天数差除以 7。对星期六执行相同的操作,然后您可以从总天数中减去星期日和星期六的数量在这一年里。这是迄今为止我发现的最有效的解决方案。
You could search for the first and the last sunday in the year and then divide the difference in days of those two dates with 7. Do the same thing for saturday and then you can subtract the number of sundays and saturdays from tho total number of days in the year. That is the most efficient solution I have found so far.
找到了这个没有 for 循环的解决方案(未经测试 http://www. phpbuilder.com/board/archive/index.php/t-10267313.html)
Found this solution without for loop (untested from http://www.phpbuilder.com/board/archive/index.php/t-10267313.html)