获取给定月份的工作日数
我想计算给定月份和年份中的工作日天数。工作日是指周一至周五。我该怎么做?
I want to calculate the number of weekdays days in a give month and year. Weekdays means monday to friday. How do i do it ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
你不需要计算这个月的每一天。您已经知道无论如何,前 28 天包含 20 个工作日。您所要做的就是确定最后几天。将起始值更改为 29。然后将 20 个工作日添加到返回值中。
You don't need to count every day in the month. You already know the first 28 days contain 20 weekdays no matter what. All you have to do is determine the last few days. Change the start value to 29. Then add 20 weekdays to your return value.
一些基本代码:
如果您的 PHP 错误警告不显示通知,请删除
@
。Some basic code:
Remove the
@
if your PHP error warning doesn't show notices.试试这个
try this one
这是我能想到的最简单的代码。
您确实需要创建一个数组或数据库表来保存假期以获得真正的“工作日”计数,但这不是所要求的,所以就在这里,希望这对某人有帮助。
This is the simplest code I could come up with.
You really would need to create an array or a database table to hold the holidays to get a true, "Working Days" count, but that wasn't what was asked, so here you go, hope this helps someone.
获取两个日期之间无节假日的工作日数:
使用示例:
输出:
链接到功能
Get the number of working days without holidays between two dates :
Use example:
Output:
Link to the function
日期对象方法:
DateObject method:
从任意日期计算一个月内的工作日:
Calculate working days in a month from any date:
查找给定月份的最后一天和工作日
然后做一个简单的 while 循环,例如:-
$cnt = 给定月份的工作日(周一至周五)总计
Find the last day and the weekday for the given month
then do a simple while loop like :-
$cnt = total of weekday (Monday to Friday) for a given month
我想出了一个非循环函数。在性能方面要好得多。看起来可能很乱,但它只需要询问 PHP 第一天是工作日和该月的天数即可:其余的都是基于逻辑的算术运算。
I've come up with a non-loop function. Much better in terms of performance. It might seem messy but it just needs to ask PHP the first day's weekday and the month's number days: the rest are arithmetical operations based on logic.
这些函数使用以下方式计算工作日数:
The functions calculate the number of weekdays using:
我创建了一个简单的函数,它接受 $first_day_of_month (星期天/星期一等)。您可以像这样找到每月的第一天:
并使用可以像这样获取的 $month_last_date :
这是函数:
I created a simple function that takes the $first_day_of_month (week day like Sunday/Monday etc). You can find out the first day of month like this:
And using the $month_last_date which can be procured like this:
Here is the function:
这会起作用
this will work