php获取指定年份下所有的周和当前周的开始和结束

  1. composer安装包
composer require nesbot/carbon
  1. 下面是代码例子,注意,仅限于国内,周一开始作为这个星期的开始,周日作为结束,不同国家可能不一样,需要注意。我国算当年的第一周,是按包含1月4日的那个星期为当年的第一个星期。
  2. 上代码:

date_default_timezone_set('Asia/Shanghai');

require __DIR__ . '/vendor/autoload.php';

function getFullWeekByYear($year = null)
{
    $p   = \Carbon\CarbonImmutable::now();
    $p   = $p->weekYear($year);
    $sum = $p->isoWeeksInYear();

    $result = [];
    for ($i = 0; $i < $sum; $i++) {
        $start    = strtotime($p->week($i + 1)->format('Y-m-d'));
        $end      = $start + 3600 * 24 * 6;
        $result[] = [$start, $end];
    }
    return $result;
}

function getNowWeek()
{
    $p     = \Carbon\CarbonImmutable::now();
    $start = strtotime($p->startOfWeek()->format('Y-m-d'));
    return [$start, $start + 3600 * 24 * 6];
}

$result = getFullWeekByYear(2018);
foreach ($result as $item) {
    echo date('Y-m-d', $item[0]) . ' ~ ' . date('Y-m-d', $item[1]) . "\n";
}

echo "================\n";

$week = getNowWeek();
echo date('Y-m-d', $week[0]), "\n";
echo date('Y-m-d', $week[1]), "\n";

你可能感兴趣的:(php)