问题描述:

I am working on a php project where I need to get the all dates for next 20 weeks from a particular date and I am trying following logic

$epochdate = strtotime("17 August 2015");

for ($i=$epochdate + 604800, $i < $epochdate + ( 604800 * 20 ); $i = $i+604800, $j++) {

echo date('Y-m-d H:i:s', $i);

echo '</br>';

}

Everything is working fine but it gave wrong date after 2015-10-19 ..here is the output

2015-08-24 00:00:00

2015-08-31 00:00:00

2015-09-07 00:00:00

2015-09-14 00:00:00

2015-09-21 00:00:00

2015-09-28 00:00:00

2015-10-05 00:00:00

2015-10-12 00:00:00

2015-10-19 00:00:00

2015-10-25 23:00:00//it should be 2015-10-26

2015-11-01 23:00:00

2015-11-08 23:00:00

2015-11-15 23:00:00

2015-11-22 23:00:00

2015-11-29 23:00:00

2015-12-06 23:00:00

2015-12-13 23:00:00

2015-12-20 23:00:00

2015-12-27 23:00:00

What is wrong here?

网友答案:

This most likely happens because of the transition from standard time to daylight time in some time zones.

Try using the DateTime class instead:

$epochdate = new DateTime("2015-08-17");
for ($i = 0; $i < 20; $i++) {
  $epochdate->modify('+1 week');
  echo $epochdate->format('Y-m-d H:i-s') . '<br>';
}

Output:

2015-08-24 00:00-00
2015-08-31 00:00-00
2015-09-07 00:00-00
2015-09-14 00:00-00
2015-09-21 00:00-00
2015-09-28 00:00-00
2015-10-05 00:00-00
2015-10-12 00:00-00
2015-10-19 00:00-00
2015-10-26 00:00-00
2015-11-02 00:00-00
2015-11-09 00:00-00
2015-11-16 00:00-00
2015-11-23 00:00-00
2015-11-30 00:00-00
2015-12-07 00:00-00
2015-12-14 00:00-00
2015-12-21 00:00-00
2015-12-28 00:00-00
2016-01-04 00:00-00

If the date comes in the day month year format as in your example you may need to use DateTime::createFromFormat() first.

网友答案:

Why did you make it so complicated?

For your logic with strtotime() you can just do that

 <?php
    $epochdate = "17 August 2015"; 
    for ($i=0; $i<=20; $i++) {
       echo date('Y-m-d H:i', strtotime($epochdate.' +'.$i.' weeks');
       echo "<br>";

    }
相关阅读:
Top