找出 PHP 中第 n 周星期一的日期?
我有一个简单的情况,用户提供了第 X 周,我需要找出该周的星期一日期(例如 12 月 12 日)。我将如何实现这一目标?我知道年份和星期。
I have a simple situation where I have a user supplied week number X, and I need to find out that week's monday's date (e.g. 12 December). How would I achieve this? I know year and week.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一些代码主要基于之前的提案:
Some code based mainly on previous proposals:
一个入门的想法:
可能需要在上述基础上添加一天。
根据您计算周数和周开始的方式,有时可能会出现错误。 (即,如果一年第一周的星期一实际上是上一年的星期一!)
彻底测试这一点 - 但我过去曾使用类似的方法进行类似的计算。
An idea to get you started:
May need to add one day to the above.
Depending on the way you are calculating week numbers and the start of the week this may sometimes be out. (i.e. if the monday in the first week of the year was actually in the previous year!)
TEST THIS THOROUGHLY - but I've used a similar approach for similar calcualtions in the past.
这将为您解决问题。它主要源自 Mihail Dimitrov 的回答,但有所简化和浓缩。如果您确实愿意,它可以是一种单线解决方案。
一些注意事项:
strtotime("Monday January $year")
将为您提供一年中第一个星期一的时间戳。您可以通过尝试验证这一点:
This will solve the problem for you. It mainly derives from Mihail Dimitrov's answer, but simplifies and condenses this somewhat. It can be a one-line solution if you really want it to be.
A couple of notes:
strtotime("Monday January $year")
will give you the timestamp of the first Monday of the year.You can validate this by trying:
由于声誉限制,我无法发布多个链接
有关详细信息,请检查
http://php.net/manual/en/function.date.php 和 http://php.net/manual/en/function.mktime .php
你可以使用这样的东西:
使用 mktime 获取本周的时间戳: $stamp = mktime(0,0,0,0,<7*x>,) {几年前使用过类似的东西,所以我不确定它是这样工作的}
然后使用 $wDay = date('N',$stamp)。现在您已经知道了星期几,星期一的时间戳应该是
mktime(0,0,0,0,<7*x>-$wDay+1,) { 'N' 参数返回 1 表示星期一,周日 6}
希望这有帮助
Due to reputation restriction i can't post multiple links
for details check
http://php.net/manual/en/function.date.php and http://php.net/manual/en/function.mktime.php
you can use something like this :
use mktime to get a timestamp of the week : $stamp = mktime(0,0,0,0,<7*x>,) {used something similar a few years back, so i'm not sure it works like this}
and then use $wDay = date('N',$stamp). You now have the day of the week, the timestamp of the monday should be
mktime(0,0,0,0,<7*x>-$wDay+1,) {the 'N' parameter returns 1 for monday, 6 for sunday}
hope this helps
输出
Out Put