使用PHP从日期(月份)确定周数

使用PHP从日期(月份)确定周数,php,mysql,Php,Mysql,我希望得到帮助,以确定一周中的某个特定日期是属于该月的第1周、第2周、第3周还是第5周。下面的代码从周一到周六返回0-7,但这不是我想要的,而是我想要能够确定的,例如今天是2016年9月19日,属于本月的第3周。我需要这方面的帮助 function getWeekday($date){ return date('w',strtotime($date)); } 你所需要的只是 ceil(date('d')/7); 所以你的函数看起来像 function getWeekday($date){

我希望得到帮助,以确定一周中的某个特定日期是属于该月的第1周、第2周、第3周还是第5周。下面的代码从周一到周六返回0-7,但这不是我想要的,而是我想要能够确定的,例如今天是2016年9月19日,属于本月的第3周。我需要这方面的帮助

function getWeekday($date){
return date('w',strtotime($date));
}
你所需要的只是

ceil(date('d')/7);
所以你的函数看起来像

function getWeekday($date){
  return ceil(date('d',strtotime($date))/7);
}

尽管要求有点奇怪。本月的第1周不是一个很好的定义,但根据您对各种答案的评论,如果日期在本月的前7天内,您只需要查看第1周。下一个7点2分,下一个7点3分,下一个7点4分,剩下的5分

输出

D   W
1   1
2   1
3   1
4   1
5   1
6   1
7   1
8   2
9   2
10  2
11  2
12  2
13  2
14  2
15  3
16  3
17  3
18  3
19  3
20  3
21  3
22  4
23  4
24  4
25  4
26  4
27  4
28  4
29  5
30  5
31  5

旧答案

简单!您需要大写字母
W
,而不是小写字母

W

ISO-8601年的周数,星期一开始的周数(在PHP 4.1.0中添加)

您正在使用的小写字母是

一周中某一天的数字表示形式

这应该可以:

 echo date('W', strtotime($date)) - date('W', strtotime("first day of this month")) + 1;

这对于DateTime对象来说非常简单,或者更确切地说是DateTimeImmutable

// Immutable so we don't need to clone the object.
$date = new DateTimeImmutable ($date, $dtz);

// We need to find out which week number the month starts at.
$start = $date->modify ("first day of this month");

// The first week - the current week + 1 == The week in the month.
$monthWeek = $date->format ("W") - $start->format ("W") + 1;

仅此而已。

谢谢,但这不是我想要的。您的回复将在第38周给我,而不是第3周。我想要的是花一个月的时间,确定这一天是属于该月的第1周还是第2周、第3周、第4周还是第5周,而这一周的起点是什么?第一天?第一天还是第一天?这就是问题所在。这一周什么时候开始,可以在周二、周三等开始吗?第一天,即每周一month@Hankey,这个回答解决了我的问题。谢谢大家让我试着回去这恐怕不是个好办法。这不仅是因为您正在使用旧函数进行日期操作,还因为这增加了许多不必要的复杂性和手动计算。请看我的答案,找到一个更干净更简单的方法。@ChristianF这更好吗?回音日期('W',strottime($date))-日期('W',strottime($date))+1;让我们来看看$dtz pls是什么变量?那是DateTimeZone对象。有关更多信息,请参阅DateTime手册。这是投掷误差1。未定义变量:dtz。2致命错误:对非对象调用成员函数format()。3。未定义的$date。请问我在你的代码中做错了什么?你需要用正确的时区信息定义$dtz变量。按照手册。顺便说一句,这是DateTime类的_construct()方法。另外,我注意到我在第二行中使用了错误的方法。刚刚将其从
format()
更改为
modify()
,对此表示抱歉。
// Immutable so we don't need to clone the object.
$date = new DateTimeImmutable ($date, $dtz);

// We need to find out which week number the month starts at.
$start = $date->modify ("first day of this month");

// The first week - the current week + 1 == The week in the month.
$monthWeek = $date->format ("W") - $start->format ("W") + 1;