PHP 获取每月的周数
因此,我有一个脚本,它返回特定月份和年份的周数。我如何从该月中获取特定日期,并确定它是该月第1,2,3,4或5周的一部分?
因此,我有一个脚本,它返回特定月份和年份的周数。我如何从该月中获取特定日期,并确定它是该月第1,2,3,4或5周的一部分?
我尝试过的最令人沮丧的事情 - 但在这里!
<?php
/**
* Returns the amount of weeks into the month a date is
* @param $date a YYYY-MM-DD formatted date
* @param $rollover The day on which the week rolls over
*/
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "00");
$elapsed = ($timestamp - $first) / $daylen;
$weeks = 1;
for ($i = 1; $i <= $elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover)) $weeks ++;
}
return $weeks;
}
//
echo getWeeks("2011-06-11", "sunday"); //outputs 2, for the second week of the month
?>
编辑:这么多“单行” - 需要变量来避免用条件重新计算。在我使用它时,折腾了一个默认的论点。
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = date('W', $when); // note that ISO weeks start on Monday
$firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
请注意,将返回;一些罕见的月份有6周的时间,与OP的预期相反。2017 年 1 月是另一个包含 6 个 ISO 周的月份 - 自 ISO 周从周一开始以来,第 1 个星期日落在去年的一周内。weekOfMonth(strtotime('Oct 31, 2011'));
6
对于 starshine531,要返回当月的索引周,请将 更改为 或 。0
return 1 +
return 0 +
return (int)
对于 Justin Stayton,对于从星期日而不是星期一开始的几周,我将使用 代替 ,如下所示:strftime('%U'
date('W'
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = strftime('%U', $when); // weeks start on Sunday
$firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
对于此版本,2017-04-30 现在为 4 月的第 6 周,而 2017-01-31 现在为第 5 周。