在一个特定月份的PHP中抓住所有星期三 [英] Grab all Wednesdays in a given month in PHP

查看:142
本文介绍了在一个特定月份的PHP中抓住所有星期三的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想写的功能:

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

任何想法?谢谢 -

Any ideas? Thanks-

推荐答案

使用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")
    );
}

用法:

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

输出:

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

请注意,这将排除结束日期,因此如果最后一天 $ y- $ m 恰好是星期三,它不会在列表中。你必须添加一天到结束日期,以包括它。要包括它,将结束日期的相对格式更改为

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,

使用PHP< 5.3

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;
}

用法:

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

与上述相同的输出(在键盘上运行)。

Same output as above (Run on Codepad).

请注意,此不适用于5.3之前的任何版本。 a>由于相对格式解析器的变化。如果要使用PHP 5.3+,您必须先将$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ m-01 (注意of)。另外,就像在DateTime版本一样,结束日期也不包括在内。

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.

进一步阅读:

  • DateTime in PHP Manual
  • Relative DateTime Formats
  • Derick Rethans: Advanced Date/Time Handling (ZendCon 10)
  • Relative item in date strings (mirror)

这篇关于在一个特定月份的PHP中抓住所有星期三的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆