0

我想生成现在开始的每个日期(时间戳),每个星期一,在特定时间,比如 16h30、17h00 和 14h00。

这段代码几乎可以工作,但小时是当前的,而不是$hours[$i],它也是一周中的当前天而不是下一个星期一

$hours = array('16h30', '17h00', '14h00');
for ($i = 0; $i < 3; $i++) {
    // how to specify the hour $hours[$i] ?
    $dates[] = strtotime("+$i weeks 0 days");
}

期望的输出:

monday 5 november, 16h30
monday 12 november, 16h30
monday 19 november, 16h30
...
4

3 回答 3

1

如果您从时间中删除“h”,PHP 将按原样理解它们,您只需将工作日名称放在字符串中即可。

$hours = array('1630', '1700', '1400');
for ($i = 0; $i < 3; $i++) {
    $dates[] = strtotime("monday +$i weeks $hours[$i]");
}

如果您需要h其余代码的 ,您可以出于此目的将其删除:

$hours = array('16h30', '17h00', '14h00');
for ($i = 0; $i < 3; $i++) {
    $dates[] = strtotime("monday +$i weeks " . 
                         join('', explode('h', $hours[$i])));
}
于 2012-11-05T11:38:17.083 回答
1

这是使用DateTime 类的解决方案:-

/**
 * Get weekly repeating dates for an event
 *
 * Creates an array of date time objects one for each $week
 * starting at $startDate. Using the default value of 0 will return
 * an array with just the $startDate, a value of 1 will return an
 * array containing $startDate + the following week.
 *
 * @param DateTime $startDate
 * @param int optional defaults to 0 number of weeks to repeat
 * @return array of DateTime objects
 */
function getWeeklyOccurences(DateTime $startDate, $weeks = 0)
{
    $occurences = array();
    $period = new DatePeriod($startDate, new DateInterval('P1W'), $weeks);
    foreach($period as $date){
        $occurences[] = $date;
    }
    return $occurences;
}

$startDate = new datetime();
$startDate->setTime(16, 30);
var_dump(getWeeklyOccurences($startDate, 52));

给出以下输出:-

array (size=53)

      0 => 
        object(DateTime)[4]
          public 'date' => string '2012-11-06 16:30:00' (length=19)
          public 'timezone_type' => int 3
          public 'timezone' => string 'UTC' (length=3)
      1 => 
        object(DateTime)[5]
          public 'date' => string '2012-11-13 16:30:00' (length=19)
          public 'timezone_type' => int 3
          public 'timezone' => string 'UTC' (length=3)
      2 => 
        object(DateTime)[6]
          public 'date' => string '2012-11-20 16:30:00' (length=19)
          public 'timezone_type' => int 3
          public 'timezone' => string 'UTC' (length=3)
      3 => 
        object(DateTime)[7]
          public 'date' => string '2012-11-27 16:30:00' (length=19)
          public 'timezone_type' => int 3
          public 'timezone' => string 'UTC' (length=3)

ETC..

然后,您可以根据需要格式化输出DateTime::format()

于 2012-11-06T13:24:30.307 回答
0

像这样的事情怎么样:使用 mktime 生成第一个日期,然后使用 strtotime:

$start_date = mktime(16, 30, 0, 11, 5, 2012);
for ($i = 0; $i < 3; $i++) {
    // how to specify the hour $hours[$i] ?
    $dates[] = strtotime("+$i weeks 0 days", $start_date);
}
于 2012-11-05T11:37:02.403 回答