Return dates of current calendar week as array in PHP5

后端 未结 2 630
谎友^
谎友^ 2021-01-16 02:30

How would I put together a PHP5 function that would find the current calendar week and return the dates of each day in the week as an array, starting on Monday? For example,

2条回答
  •  独厮守ぢ
    2021-01-16 03:12

    Lessee. . First, to avoid any timezone issues I'd peg to noon on the day you want to compare against, so an hour either way won't cause any problems.

    $dateCompare = time(); // replace with a parameter
    $dateCompare = mktime(12, 0, 0, date('n', $dateCompare), 
          date('j', $dateCompare), date('Y', $dateCompare));
    

    Then find the day of week of your date.

    $dow = date('N', $dateCompare);
    

    1 is Monday, so figure out how many days from Monday we are.

    $days = $dow - 1;
    

    Now subtract days worth of seconds until you get back to Monday.

    $dateCompare -= (3600 * 24 * $days);
    

    Now assemble your array of days.

    $output = array();
    for ($x = 0; $x < 7; $x++) {
        $output[$x] = $dateCompare + ($x * 24 * 3600);
    }
    

    This is an array of timestamps, but you could store the dates as strings if you prefer.

提交回复
热议问题