PHP tool method to get the date range of the Nth week

PHP's date library function is very powerful. For example, to get the week number of a certain timestamp in the current year, you can use date('W', $timestamp) to achieve it. But if you know the week number, you want to get this week. How to deal with the corresponding time interval?

There is no corresponding method in the PHP library function, so I encapsulated the following method:

/**
     * 获取第n周的日期区间
     * @param [int] $no 要获取第几周的日期
     * @param [string] $dateFormat 日期格式
     * @return string 日期区间字符串
     */
    public static function getDateByWeekNum($no, $dateFormat = 'Y.m.d'){
        $newYearDate = strtotime(date('Y').'-01-01 00:00:01');
        //当前是这个星期的第几天
        $dateOrder = date('N', $newYearDate);
        //国际惯例每年第一个星期一所在的周为第一周, 所以如果元旦是周一,则第一周就是当前这周,否则第一周从下周开始
        $leftDaysToNextMonday = $dateOrder > 1?7-$dateOrder+1:0;
        //第N周的起始天应该是从第N-1周+1天开始的
        $no--;
        $startDate = strtotime("+{$no} week", strtotime("+$leftDaysToNextMonday days", $newYearDate));
        $endDate = strtotime('+6 days', $startDate);
        return date($dateFormat, $startDate).'~'.date($dateFormat, $endDate);
    }

Guess you like

Origin blog.csdn.net/one_and_only4711/article/details/118547536