Asi*_*ain 13 php arrays date week-number
我有一系列随机日期(不是来自MySQL).我需要将它们按周分组为第1周,第2周,依此类推至第5周.
我有的是这个:
$dates = array('2015-09-01','2015-09-05','2015-09-06','2015-09-15','2015-09-17');
Run Code Online (Sandbox Code Playgroud)
我需要的是通过提供日期来获取月份周数的函数.
我知道我可以通过这样做获得
date('W',strtotime('2015-09-01'));
周数,但本周数是年(1-52)之间的数字,但我只需要一个月的周数,例如2015年9月有5周:
我应该能够通过提供日期来获得第一周的第1周
$weekNumber = getWeekNumber('2015-09-01') //output 1;
$weekNumber = getWeekNumber('2015-09-17') //output 3;
Run Code Online (Sandbox Code Playgroud)
And*_*ers 26
我认为这种关系应该是真的(?)并派上用场:
Week of the month = Week of the year - Week of the year of first day of month + 1
Run Code Online (Sandbox Code Playgroud)
用PHP实现,你得到这个:
function weekOfMonth($date) {
//Get the first day of the month.
$firstOfMonth = strtotime(date("Y-m-01", $date));
//Apply above formula.
return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;
}
Run Code Online (Sandbox Code Playgroud)
要获得以星期日开始的周数,只需将其替换date("W", ...)为strftime("%U", ...).
你可以使用下面的功能,完全评论:
/**
* Returns the number of week in a month for the specified date.
*
* @param string $date
* @return int
*/
function weekOfMonth($date) {
// estract date parts
list($y, $m, $d) = explode('-', date('Y-m-d', strtotime($date)));
// current week, min 1
$w = 1;
// for each day since the start of the month
for ($i = 1; $i <= $d; ++$i) {
// if that day was a sunday and is not the first day of month
if ($i > 1 && date('w', strtotime("$y-$m-$i")) == 0) {
// increment current week
++$w;
}
}
// now return
return $w;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
核心方式是
function weekOfMonth($date) {
$firstOfMonth = date("Y-m-01", strtotime($date));
return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
}
Run Code Online (Sandbox Code Playgroud)