获取特定时刻每周的日期

时间:2012-11-05 11:19:35

标签: php date datetime

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

此代码几乎可以使用,但小时是当前的小时,而不是$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
...

3 个答案:

答案 0 :(得分: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])));
}

答案 1 :(得分:1)

以下是使用DateTime classes的解决方案: -

/**
 * 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)

等。

然后,您可以使用DateTime::format()

格式化输出

答案 2 :(得分: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);
}