【问题标题】:How to dynamically increment dates using strtotime?如何使用 strtotime 动态增加日期?
【发布时间】:2017-04-02 23:33:10
【问题描述】:

我需要从起点获得 26 个日期。下一个日期从上一个日期开始。硬编码一切都是疯狂的......所以我想知道我怎样才能动态地做到这一点?有没有更聪明的方法?我希望在第二次约会之后增加。也许有一个 for 循环?

    <?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>';
    ?>

【问题讨论】:

  • 尝试先用语言标记它,然后再用更深奥的东西。
  • 您希望将日期增加多少?是固定数量还是变化数量?
  • @user3299379:在第二个日期之后总是 +14 天
  • 看到这个是db相关的;为什么不在插入/更新期间直接在查询中执行此操作,然后在 mysql 中添加/减去,并在需要时使用WHERE 子句?这就是我从中得到的。如果我们确切地知道这是为了什么,也许 mysql 解决方案会比 php 更好。
  • @SebastianFarham 这个关于 Stack 的问答将更好地解释/概述我的意思 stackoverflow.com/q/7820322/1415724 和手动参考 dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

标签: php for-loop increment strtotime


【解决方案1】:

这个怎么样:

// 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;
}

【讨论】:

    【解决方案2】:

    可能最简单的方法是使用数组

    $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>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多