Get Start and End Days for a Given Week in PHP

前端 未结 16 1874
囚心锁ツ
囚心锁ツ 2020-12-01 03:49

I\'m trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can\'t seem to figure it out.

For example,

16条回答
  •  既然无缘
    2020-12-01 04:16

    Here's my version, which uses a similar notion to Clay's:

    /**
     * Start of the week
     *
     * 0 = Sun, 1 = Mon, etc.
     */
    define( 'WEEK_START', 0 );
    
    /**
     * Determine the start and end dates for
     * the week in which the specified date
     * falls
     *
     * @param $date Date in week
     * @param $start Week start (out)
     * @param $end Week end (out)
     */
    function week_bounds( $date, &$start, &$end ) {
        $date = strtotime( $date );
        // Find the start of the week, working backwards
        $start = $date;
        while( date( 'w', $start ) > WEEK_START ) {
            $start -= 86400; // One day
        }
        // End of the week is simply 6 days from the start
        $end = date( 'Y-m-d', $start + ( 6 * 86400 ) );
        $start = date( 'Y-m-d', $start );
    }
    

    Lightly tested. Code may not be bulletproof, or handle dates in the far past or future. Use at your own risk. Do not immerse the code in water. Do not show the code to those of a nervous disposition, or with a hatred of the dollar sign. Not tested on animals. Safe for use by vegetarians. Author warrants that the code will never, ever speak to you. In the unlikely event that the code does try to engage you in conversation, the author advises you to disregard any and all advice it gives.

提交回复
热议问题