我有一个随机日期数组(不是来自 MySQL)。我需要按周将它们分组为第 1 周、第 2 周,依此类推直至第 5 周。
我所拥有的是这样的:
$dates = array('2015-09-01','2015-09-05','2015-09-06','2015-09-15','2015-09-17');
我需要的是一个通过提供日期来获取该月的周数的函数。
我知道我可以通过这样做获得周数date('W',strtotime('2015-09-01'));
但这周数是年份(1-52)之间的数字,但我只需要该月的周数,例如2015年9月有5周:
- 第 1 周 = 第 1 至第 5 周
- 第 2 周 = 第 6 日至第 12 日
- 第三周 = 13 日至 19 日
- 第 4 周 = 20 日至 26 日
- 第 5 周 = 27 日至 30 日
我应该能够通过提供日期来获得 Week1 周
例如
$weekNumber = getWeekNumber('2015-09-01') //output 1;
$weekNumber = getWeekNumber('2015-09-17') //output 3;
我认为这种关系应该是真实的并且派上用场:
Week of the month = Week of the year - Week of the year of first day of month + 1
我们还需要确保正确处理上一年的“重叠”周 - 如果 1 月 1 日位于第 52 或 53 周,则应将其计为第 0 周。以类似的方式,如果 12 月的某一天位于明年的第一周,应该算作 53。(此答案的先前版本未能正确执行此操作。)
<?php
function weekOfMonth($date) {
//Get the first day of the month.
$firstOfMonth = strtotime(date("Y-m-01", $date));
//Apply above formula.
return weekOfYear($date) - weekOfYear($firstOfMonth) + 1;
}
function weekOfYear($date) {
$weekOfYear = intval(date("W", $date));
if (date('n', $date) == "1" && $weekOfYear > 51) {
// It's the last week of the previos year.
return 0;
}
else if (date('n', $date) == "12" && $weekOfYear == 1) {
// It's the first week of the next year.
return 53;
}
else {
// It's a "normal" week.
return $weekOfYear;
}
}
// A few test cases.
echo weekOfMonth(strtotime("2020-04-12")) . " "; // 2
echo weekOfMonth(strtotime("2020-12-31")) . " "; // 5
echo weekOfMonth(strtotime("2020-01-02")) . " "; // 1
echo weekOfMonth(strtotime("2021-01-28")) . " "; // 5
echo weekOfMonth(strtotime("2018-12-31")) . " "; // 6
要获得从星期日开始的周数,只需替换date("W", ...)
with strftime("%U", ...)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)