Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

datetime - Grab all Wednesdays in a given month in PHP

This is the function I'm trying to write:

function getWednesdays($month, $year) {
   // Returns an array of DateTimes representing all Wednesdays this month.
}

Any ideas? Thanks-

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With PHP5.3

function getWednesdays($y, $m)
{
    return new DatePeriod(
        new DateTime("first wednesday of $y-$m"),
        DateInterval::createFromDateString('next wednesday'),
        new DateTime("last day of $y-$m")
    );
}

Usage:

foreach (getWednesdays(2010, 11) as $wednesday) {
    echo $wednesday->format("l, Y-m-d
");
}

Output:

Wednesday, 2010-11-03
Wednesday, 2010-11-10
Wednesday, 2010-11-17
Wednesday, 2010-11-24

Note that this will exclude the end date, so if the last day of $y-$m happens to be a Wednesday, it won't be in the list. You have to add a day to the end date, to include it. To include it, change the relative format in the end date to

new DateTime("next month $y-$m-01")

which will then set the end date to the first day of the next month,


With PHP < 5.3

function getWednesdays($y, $m)
{
    $ts  = strtotime("first wednesday $y-$m-01");
    $end = strtotime("last wednesday $y-$m");
    $wednesdays = array();
    while($ts <= $end) {
        $wednesdays[] = $ts;
        $ts = strtotime('next wednesday', $ts);
    }
    return $wednesdays;
}

Usage:

foreach (getWednesdays(2010, 11) as $wednesday) {
    echo date("l, Y-m-d
", $wednesday);
}

Same output as above (Run on Codepad).

Note that this does not work for any version prior to 5.3 due to changes in the relative formats parser. If you want to use this with PHP 5.3+ you have to change first Wednesday $y-$m-01 to first Wednesday of $y-$m-01 (mind the "of"). Also, just like in the DateTime version, the end date will not be included.


Further reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...