I have the following php code:
$date = new DateTime();
$date->setTimeZone(new DateTimeZone('America/New_York'));
$index = 0;
while( $index <10){
$date->modify('+'. $index .' day');
print $date->format('Y-m-d') . ' - index: ' . $index . '<br/>';
$index++;
}
What this script should do: it should display todays date and the next 9 dates for the following days: ( I also printed the $index value each time to make sure the index it's right all time).
What it actually displays:
2017-05-29 - index: 0
2017-05-30 - index: 1
2017-06-01 - index: 2
2017-06-04 - index: 3
2017-06-08 - index: 4
2017-06-13 - index: 5
2017-06-19 - index: 6
2017-06-26 - index: 7
2017-07-04 - index: 8
2017-07-13 - index: 9
NOTE: See how from date 2017-06-01 jumps to 2017-06-04 and then to 2017-06-08 and so on.
I have no idea why this happens, can someone tell me? Is this even the right approach ?
As you want to add 1 day on every iteration, you don't need to use the index on the sum, just use $date->modify("+1 day");
.
Also, put the line where you print the date before you modify it.
What happens in your code is that you start adding 0 on the first iteration, which then you print the actual day. Next iteration, you add 1, so tomorrow is printed. Next iteration, you add 2, and skip 1 day. Next, add 3, and skip 2 days... And this over and over.
不要更改$index
的值使其等于1,甚至不要尝试在modify()
函数中执行“ +1天”
for($i=1;$i<=10;$i++)
echo date("y-m-d",strtotime($i." day"))."<br />";
Use this loop
$begin = new DateTime("2017-05-29");
$end = new DateTime("2017-06-8");
$end = $end->modify('+1 day');
$interval = DateInterval::createFromDateString('1 day');
$index = 0;
foreach ($period as $dt) {
if ($index == 9) {
break;
}
echo $dt->format("Y-m-d");
$index = $index + 1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.