PHP从特定开始日期开始重复一周

时间:2013-11-07 16:12:00

标签: php arrays date

我正在尝试设置和看起来像这样的数组:

$dates = array(
    [0] => "07/11/2013",
    [1] => "14/11/2013",
    [2] => "21/11/2013",
    [3] => "28/11/2013",
    [4] => "05/12/2013",
    [5] => "12/12/2013");

我愿意使用它,但是因为我希望明年再次重复这一点,我宁愿让PHP这样做,并为我输入一个数组。我知道如何将其限制为我想要的特定金额,但如果我想以08/11/2013为例,我不知道如何在当前日期或特定日期添加一周。

我快速看了一下,似乎找不到任何可以做到这一点。

我只需要一个脚本来添加一周到当前日期,此时是每周四,然后将其添加到数组中。

我唯一的问题是我不确定如何指定日期,然后每次都添加一周。我假设for循环在这里最好。

4 个答案:

答案 0 :(得分:4)

使用DateTime课程。在PHP 5.3.0中引入了DateInterval和DatePeriod类,因此以下解决方案仅适用于PHP> = 5.3.0:

$start = new DateTime('2013-11-07');
$end = new DateTime('2013-12-31');
$interval = new DateInterval('P1W');  // one week

$p = new DatePeriod($start, $interval, $end);

foreach ($p as $w) {
    $weeks[] = $w->format('d-m-Y');
}

Demo!

正如Glavic在comments below中所说,这也可以使用modify()方法在以前版本的PHP中完成:

$start = new DateTime('2013-11-07');
$end = new DateTime('2013-12-31');

$weeks = array();
while ($start < $end) {
    $weeks[] = $start->format('d-m-Y');
    $start->modify('+1 week');
}

Demo.

答案 1 :(得分:1)

strtotime做你需要的事情

 $nextWeek = strtotime('08/11/2013 + 1 week'); 

如果您需要8次,请将其循环8次。您可以使用$start$numWeek创建一个函数,以返回一个$numWeeks + 1值的数组(添加了开头)

function createDateList($start, $numWeeks){
    $dates = array($start);// add first date
    // create a loop with $numWeeks illiterations:
    for($i=1;$<=$numWeeks; $i++){
        // Add the weeks, take the first value and add $i weeks to it
        $time = strtotime($dates[0].' + '.$i.' week'); // get epoch value
        $dates[] = date("d/M/Y", $time); // set to prefered date format

    }
    return $dates;
}

答案 2 :(得分:1)

您可以使用strtotime('+1 week', $unixTimestamp)

<?php
    $startDate = '2013-11-07';
    $endDate = '2013-12-31';

    $startDateUnix = strtotime($startDate);
    $endDateUnix = strtotime($endDate);

    $dates = array();

    while ($startDateUnix < $endDateUnix) {
        $dates[] = date('Y-m-d', $startDateUnix);
        $startDateUnix = strtotime('+1 week', $startDateUnix);
    }

    print_r($dates);
?>

输出:

Array
(
    [0] => 2013-11-07
    [1] => 2013-11-14
    [2] => 2013-11-21
    [3] => 2013-11-28
    [4] => 2013-12-05
    [5] => 2013-12-12
    [6] => 2013-12-19
    [7] => 2013-12-26
)

DEMO

(以任何方式格式化date()来获取您想要的格式。

答案 3 :(得分:-1)

strtotime()功能可以在这里工作吗?

$nextweek = strtotime('thursday next week');
$date = date('d/m/Y', $nextweek);

创建一个包含今天(或星期四)和下一个4:

的5元素数组
for ($a = 0; $a < 5; $a++)
{
  $thur = date('d/m/Y', strtotime("thursday this week + $a weeks"));
  $dates[] = $thur;
}
相关问题