【问题标题】:How many of a certain week day has passed this month本月过去了多少天
【发布时间】:2013-05-18 04:43:22
【问题描述】:

我有一个日历,我想让事件在每月的某个工作日重复。一些例子是:

  • 每月的第四个星期二重复
  • 每月的第二个星期五重复一次
  • 等等……

我需要的是能够找出本月到目前为止已经过去了多少工作日(例如星期二)。

I found some code 返回星期一过去了多少个。

$now=time() + 86400;
if (($dow = date('w', $now)) == 0) $dow = 7; 
$begin = $now - (86400 * ($dow-1));

echo "Mondays: ".ceil(date('d', $begin) / 7)."<br/>";

这很好用,但我如何才能确定任何工作日?我似乎无法理解代码来完成这项工作。

【问题讨论】:

  • 我会找到您需要的工作日的第一次出现 [通过从月初开始循环,在最坏的情况下直到 7 日],然后只需添加 7*(n-1)days 即可找到n-th.
  • “我似乎无法理解代码来完成这项工作。” --- 那是因为琐碎的代码应该从头开始编写
  • 查看this answer

标签: php date


【解决方案1】:

strtotime 对于这种事情真的很有用。 Here are lists of the supported syntax。使用您在每个月的第二个星期五重复的示例,我为您编写了以下简单的 sn-p:

<?php
    $noOfMonthsFromNow=12;
    $dayCondition="Second Friday of";

    $months = array();
    $years = array();
    $currentMonth = (int)date('m');
    for($i = $currentMonth; $i < $currentMonth+$noOfMonthsFromNow; $i++) {
        $months[] = date('F', mktime(0, 0, 0, $i, 1));
        $years[] = date('Y', mktime(0, 0, 0, $i, 1));
    }
    for ($i=0;$i<count($months);$i++){
        $d = date_create($dayCondition.' '.$months[$i].' '.$years[$i]); 
        if($d instanceof DateTime) echo $d->format('l F d Y H:i:s').'<br>';
    }
?>

这可以在以下位置进行测试:http://www.phpfiddle.org/lite/

【讨论】:

  • 是的,这就是我需要的。 This answer 也很有帮助。感谢您的帮助!
【解决方案2】:
$beginningOfMonth = strtotime(date('Y-m-01')); // this will give you the timestamp of the beginning of the month
$numTuesdaysPassed = 0;
for ($i = 0; $i <= date('d'); $i ++) { // 'd' == current day of month might need to change to = from <= depending on your needs
    if (date('w', $beginningOfMonth + 3600 * $i) == 2) $numTuesdaysPassed ++; // 3600 being seconds in a day, 2 being tuesday from the 'w' (sunday == 0)
}

不确定这是否可行,可能有更好的方法;现在没有办法测试它,但希望这能让你走上正轨! (我在日期数学上也有些迷惑,尤其是时区)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多