正如标题所说,我一直在谷歌搜索它,但没有任何线索。
这就是事情,假设我有一个带整数参数的函数。当我援引它,即scoutWeekly(1)
时,它列出了本月的第一周(1月28日 - 2月3日)。如果我给出函数的参数2
,它会列出本月的第二周(2月4日 - 2月10日)。所以...这一切都应该是相对于这一天,例如,如果它被引用scoutWeekly(1)
,它跳到(1月28日 - 2月3日)
你们有任何线索或片段吗?
function weeks($month, $year)
{
$num_of_days = date("t", mktime(0, 0, 0, $month, 1, $year));
$lastday = date("t", mktime(0, 0, 0, $month, 1, $year));
$no_of_weeks = 0;
$count_weeks = 0;
while ($no_of_weeks < $lastday)
{
$no_of_weeks += 7;
$count_weeks++;
}
return $count_weeks;
}
function getRangeByWeek($weekNo)
{
$firstDayOfCurrentMonth = date('Y-m-01');
$globalWeek = intval(date('W', strtotime($firstDayOfCurrentMonth)));
$globalYear = intval(date('Y', strtotime($firstDayOfCurrentMonth)));
$globalMonth = intval(date('m', strtotime($firstDayOfCurrentMonth)));
$totalNumberOfWeeks = weeks($globalMonth, $globalYear);
$date = new DateTime();
$result = [];
for ($i = 1; $i <= $totalNumberOfWeeks; $i++)
{
$startDate = $date->setISODate($globalYear, $globalWeek)->format("d M");
$endDate = $date->setISODate($globalYear, $globalWeek, 7)->format("d M");
$result[$i] = $startDate . '-' . $endDate;
$globalWeek++;
}
return $result[$weekNo];
}
echo getRangeByWeek(1);
产量
28 Jan-03 Feb
有一种更简单的方法......
function scoutWeekly($n) {
// today's date
$today = new DateTime();
// set to first day of the month
$today->setDate($today->format('Y'), $today->format('m'), 1);
// get the Monday earlier
$today->sub(new DateInterval('P' . ($today->format('N') - 1) . 'D'));
// add the required number of weeks
if ($n > 1) {
$today->add(new DateInterval('P' . ($n - 1) . 'W'));
}
// and format the result
return $today->format('d M') . '-' . $today->add(new DateInterval('P6D'))->format('d M');
}
echo scoutWeekly(1)
输出:
28 Jan-03 Feb
我是OP
这是已解决的答案:
private static function addScoutWeek(int $addNumb = null) : array
{
$addStart = Carbon::now()->startOfMonth()->addWeek($addNumb)->startOfWeek();
$interval = new \DateInterval('P1D');
$addEnd = Carbon::now()->startOfMonth()->addWeek($addNumb)->endOfWeek();
$dateRange = new \DatePeriod($addStart, $interval, $addEnd);
foreach ($dateRange as $date) {
$arrOfDate[] = $date;
}
return $arrOfDate;
}
案件结案