Return dates of current calendar week as array in PHP5

后端 未结 2 615
谎友^
谎友^ 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.

    0 讨论(0)
  • 2021-01-16 03:13

    I suppose a solution would be to start by getting the timestamp that correspond to last monday, using strtotime :

    $timestampFirstDay = strtotime('last monday');
    


    But if you try with today (thursday), with something like this :

    $timestampFirstDay = strtotime('last thursday');
    var_dump(date('Y-m-d', $timestampFirstDay));
    

    you'll get :

    string '2010-02-18' (length=10)
    

    i.e. last week... For strtotime, "last" means "the one before today".

    Which mean you'll have to test if today is "last monday" as returned by strtotime plus one week -- and, if so, add one week...

    Here's a possible (there are probably smarter ideas) solution :

    $timestampFirstDay = strtotime('last monday');
    if (date('Y-m-d', $timestampFirstDay) == date('Y-m-d', time() - 7*24*3600)) {
        // we are that day... => add one week
        $timestampFirstDay += 7 * 24 * 3600;
    }
    


    And now that we have the timestamp of "last monday", we can write a simple for loop that loops 7 times, adding 1 day each time, like this :

    $currentDay = $timestampFirstDay;
    for ($i = 0 ; $i < 7 ; $i++) {
        echo date('Y-m-d', $currentDay) . '<br />';
        $currentDay += 24 * 3600;
    }
    

    Which will give us this kind of output :

    2010-02-22
    2010-02-23
    2010-02-24
    2010-02-25
    2010-02-26
    2010-02-27
    2010-02-28
    


    Now, up to you to :

    • Modify that for loop so it stores the dates in an array
    • Decide which format you want to use for the date function

    Have fun ;-)

    0 讨论(0)
提交回复
热议问题