[英]use php to increment a date one week at a time with 10 iterations
I want to increment a start date by 1 week 10 times. 我想将开始日期增加1周10次。 This code doesn't work:
此代码不起作用:
<?php
$start_date = "06/25/2012";
$date = strtotime($start_date);
$X=1;
while ($X <= 10) {$X++; $Y=7*$X;
$date = strtotime("+ $Y days", $date);
echo date('m/d/Y', $date)."<br>";
}
gives: 得到:
07/09/2012
07/30/2012
08/27/2012
10/01/2012
11/12/2012
12/31/2012
02/25/2013
04/29/2013
07/08/2013
09/23/2013
This is wrong! 这是错的!
May be you are looking for this: Online Example 可能你正在寻找这个: 在线示例
$start_date = "06/25/2012";
$date = strtotime($start_date);
$X=1;
while ($X <= 10) {
$X++;
$date = strtotime("+1 weeks", $date);
echo date('m/d/Y', $date)."<br>";
}
Using DateTime
objects: 使用
DateTime
对象:
$date = new DateTime('2012-06-25');
for ($i = 1; $i <= 10; $i++) {
$date->modify('+1 week');
echo $date->format('m/d/Y');
}
Ideone: https://ideone.com/7mVkmW Ideone: https ://ideone.com/7mVkmW
Try this code. 试试这个代码。 This will give you list of 1 week period dates 50 times.
这将为您提供50周的1周期限列表。
<?php
$date = "05/01/2016";
$weekDates = '';
for ( $i = 1; $i <= 50; $i++ ) {
$date = date("m/d/Y", strtotime("+1 weeks", strtotime($date)));
$weekDates .= $date . '<br>';
}
echo $weekDates;
Answer: 回答:
<?php
$start_date = "06/25/2012";
$date = strtotime($start_date);
$newDate = $date;
for ($x = 1; $x<=10; $x++)
{
$newDate = $newDate + (86400*7);//adding the amount of seconds in a week
$buffer = date("n/j/Y", $newDate);
echo "{$buffer}<br>";
}
Explanation of the code: 代码说明:
What the previous code does is it first converts the date "06/25/2012"
into a unix timestamp. 以前的代码所做的是它首先将日期
"06/25/2012"
转换为unix时间戳。 A unix timestamp is an integer value that represents how much time (in seconds) has passed since January 1st of 1970. In the previous code, both $date
and $newDate
are unix timestamp values that look like the following big number: 1464330512
unix时间戳是一个整数值,表示自1970年1月1日以来经过的时间(以秒为单位)。在前面的代码中,
$date
和$newDate
都是unix时间戳值,看起来像以下大数字: 1464330512
From there, you want to create a loop. 从那里,你想要创建一个循环。 I preferred to use a
for
loop because it is very easy to read and suits your purpose. 我更喜欢使用
for
循环,因为它非常易于阅读并且适合您的目的。 A while
loop can also be done, though you would have to create a count
of sorts if you choose that loop instead. 也可以使用
while
循环,但如果选择该循环,则必须创建排序count
。
From there, what the code above does is that it modifies $newDate
on every loop by adding the amount of seconds in a week to it ( 86400*7
). 从那里开始,上面的代码是通过在一周内为它添加秒数(
86400*7
)来修改每个循环上的$newDate
。 After altering $newDate
, the $buffer
value then converts the $newDate
to the same format as your original date, and echoes it. 改变后
$newDate
,在$buffer
值,那么转换$newDate
以相同的格式,你原来的日期,并呼应它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.