动态地找不到从今天起每周日期返回数组的功能

问题描述 投票:0回答:3

正如标题所说,我一直在谷歌搜索它,但没有任何线索。

这就是事情,假设我有一个带整数参数的函数。当我援引它,即scoutWeekly(1)时,它列出了本月的第一周(1月28日 - 2月3日)。如果我给出函数的参数2,它会列出本月的第二周(2月4日 - 2月10日)。所以...这一切都应该是相对于这一天,例如,如果它被引用scoutWeekly(1),它跳到(1月28日 - 2月3日)

你们有任何线索或片段吗?

php date datetime php-carbon
3个回答
1
投票
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);
  1. 从当月的第一天开始提取全球周,并且需要年份和月份
  2. 在本月完成了整周
  3. 创建空DateTime实例以执行简单计算并获取全局周的第一个日期
  4. 增加全球周数,直至当月的总周数
  5. 无论结果如何,我都将索引保留为当月的周数
  6. 从当月返回当前周数的日期范围

产量

28 Jan-03 Feb

Demo


0
投票

有一种更简单的方法......

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

Demo on 3v4l.org


0
投票

我是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;
    }

案件结案

© www.soinside.com 2019 - 2024. All rights reserved.