doushang8512
doushang8512
2017-04-02 23:33
浏览 68
已采纳

如何使用strtotime动态增加日期?

I need to get 26 dates from a starting point. The next date starting from the previous one. It would be insane to hard code everything... So I was wondering how can I do this dynamically? Is there a smarter way? I'm looking to increment after the second date. Maybe with a for loop?

    <?php
    //incrementing dates for bi-weekly (26 periods// 26 dates)
    $firstdate = strtotime("+17 days", strtotime("2017-04-03"));//1
    $i = date("Y-m-d", $firstdate); echo date("Y-m-d", $firstdate);//echo for testing
    echo'<br>';
    $seconddate =strtotime("+14 days", strtotime($i));//2
    $ii = date("Y-m-d", $seconddate); echo date("Y-m-d", $seconddate);//echo for testing
    echo'<br>';
    ?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duangai9678
    duangai9678 2017-04-02 23:50
    已采纳

    How about this:

    // initialize an array with your first date
    $dates = array(strtotime("+17 days", strtotime("2017-04-03")));
    
    // now loop 26 times to get the next 26 dates
    for ($i = 1; $i <= 26; $i++) {
        // add 14 days to previous date in the array
        $dates[] = strtotime("+14 days", $dates[$i-1]);
    }
    
    // echo the results
    foreach ($dates as $date) {
        echo date("Y-m-d", $date) . PHP_EOL;
    }
    
    点赞 评论
  • dongxin2734
    dongxin2734 2017-04-03 00:00

    Probably the easiest way to do this would be with an array

    $myDates = [];
    $firstdate = strtotime("+17 days", strtotime("2017-04-03"));
    array_push($myDates, date("Y-m-d",$firstdate));
    for($i=0;$i<25;$i++){
        $lastdate = $myDates[$i];
        $nextdate = strtotime("+14 days", strtotime($lastdate));
        array_push($myDates,date("Y-m-d",$nextdate));
    }    
    
    echo "<pre>".var_dump($myDates)."</pre>";
    
    点赞 评论

相关推荐