简体   繁体   中英

Php date issue clashing with this year & next year

I get this outcome when I do the week of each year

week of45 date:2017-11-06
week of46 date:2017-11-13
week of47 date:2017-11-20
week of48 date:2017-11-27
week of49 date:2017-12-04
week of50 date:2017-12-11
week of51 date:2017-12-18
week of52 date:2017-12-25
week of1 date:1969-12-31
week of2 date:1969-12-31
week of3 date:1969-12-31
week of4 date:1969-12-31
week of5 date:1969-12-31

As you can see when it starts from 1 again, the date gets messed up, here is the code:

for($i=0;$i< 13;$i++) {
    $weekNumnew = $weekNum + $i;
    $week_date = date('Y-m-d', strtotime("$thisYear-W$weekNumnew-1")); 
    if($weekNumnew > '52'){
        $weekNumnew = $weekNumnew - 52;
        $week_date = date('Y-m-d', strtotime("$nextyear-W$weekNumnew-1"));
    }
    echo "week of" . $weekNumnew . " date:" .$week_date . "<br>";
}

$weekNumnew starts from 45 it increase each week depending on the week of year date. Also $thisYear = '2017' & $nextyear = '2018' Is there a way I can fix this? I thought it would be fixed when I added next year but it did not work, can anyone help?

You can use a combination of DateInterval and DatePeriod to generate these data for you:

<?php

$start = new DateTime('now');
$end = new DateTime('+3 years');

$interval = DateInterval::createFromDateString('1 week');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $week) {
  $monday = $week->modify('monday this week');
  printf("Week %d. Date: %s \n", $monday->format('W'), $monday->format('Y-m-d'));
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM