2

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

  • 每个月的第 4 个星期二重复
  • 每个月的第二个星期五重复
  • 等等...

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

我找到了一些代码,它返回了多少星期一已经过去。

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

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

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

4

2 回答 2

1

strtotime对于这种事情真的很有用。以下是支持的语法列表。使用您每个月的第二个星期五重复的示例,我为您编写了以下简单的代码段:

<?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/

于 2013-05-23T00:54:40.207 回答
0
$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)
}

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

于 2013-05-23T00:54:24.233 回答