在PHP中,如何知道本月到今天为止已经过去了多少个星期一?
假设今天是 2011 年 2 月 21 日(星期一)。这是本月的第三个星期一。如果给出日期作为输入,我如何知道在此之前已经过了多少个星期一?
在PHP中,如何知道本月到今天为止已经过去了多少个星期一?
Assume today is Feb 21, 2011 ( Monday ). It is the third Monday of this month. If date is given as input, How can I know how many Mondays have passed before it?
In PHP, how to know how many mondays have passed in this month uptil today?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对我有用......
编辑:也包括今天的星期一
works for me....
EDIT: includes today's monday too
这听起来像是一个非常简单的除法计算。从当前日期减去上周一过去的天数(例如:星期三 = -2),然后除以 7,然后
ceil()
将其向上舍入。编辑:这将包括当前星期一的数字,返回“3”表示 21 日星期一。
That sounds like a pretty straightforward division calculation. From the current date, subtract number of days past last monday (example: wednesday = -2), divide it by 7 and
ceil()
it to round it up.EDIT: That will include the current monday in the number, returning "3" for monday 21st.
希望这对您有用!我刚把它卷起来。
“小心上面代码中的错误;我只是证明了它的正确性,没有尝试过。”
工作正常据我所知
Hope this is of use to you! i've just rolled it up.
"Beware of bugs in the above code; I have only proved it correct, not tried it."
Works OK afaik
您可以循环遍历到现在为止的所有日子并计算星期一:
尚未测试此脚本
You could loop through all the days until now and count the mondays:
Haven't tested this script
试试这个...
Try this...
另一种方法是找到今天是一周中的哪一天,通过一些神奇的
strtotime()
找到该月的第一个这样的日子,然后计算它与现在之间的差异(以周为单位)。请参阅下面的函数,该函数将采用Ymd
格式的date()
并返回该月的哪个工作日。注意:
strtotime
需要详细,包括“of”和月份:“2011-02 的第一个星期一”,否则 提前一天。当我测试边缘情况时,这让我很恼火。还添加了一些展示胡椒,这是完全可选的,但我觉得很喜欢。
Another way is to find what day of the week is today, find the first such day of the month via some magic
strtotime()
, then calculate the difference between that and now in weeks. See below for a function that will take aY-m-d
formatteddate()
and return which weekday of the month it is.Note:
strtotime
needs to be verbose, including "of" and the month: "first Monday of 2011-02" otherwise it advances one day. This bit me when I was testing edge cases.Also added some display pepper which is completely optional but I felt like it.