Question

I am using the following lines to calculate a 4-week interval in PHP. This uses a fixed date ($calStart) as basis for the calculation and ends the interval with the last day of the selected year ($rangeEnd / $selYear) which works well so far.

Example: If the selected year is 2015 than the first date in my range here should be 2015-01-16 as the first interval date in the selected year.

Can someone here tell me how I can set this so that $rangeDays only starts with the first interval date in the selected year instead of returning all intervals since the $calStart date (which is what it does at the moment) ?

$calStart = new DateTime('2014-01-17');
$interval = DateInterval::createFromDateString('4 weeks');
$rangeEnd = new DateTime($selYear . '-12-31');
$rangeDays = new DatePeriod($calStart, $interval, $rangeEnd);

Many thanks for any help with this, Tim.

Was it helpful?

Solution

You can try with:

$calStart = new \DateTime('2014-01-17');
$calYear = $calStart->format('Y');
if ($selYear !== $calYear) {
    $day = (int) $calStart->format('z') + date('z', mktime(0,0,0,12,31,$calYear)) * ($selYear - $calYear);
    $calStart->setDate($selYear, 1, $day % 28);
}

Edit:

This one is more complex:

$calStart = new \DateTime('2014-01-17');
$calYear = (int) $calStart->format('Y');
if ($selYear !== $calYear) {
    $days = (int) $calStart->format('z') + 1; // get day in a year. +1 is because it starts with 0
    for ($i = $calYear; $i < $selYear; $i++) {
        $days -= (date('z', mktime(0,0,0,12,31,$i)) + 1) % 28; // remove from start day a modulo of 28 days, every year the date is lower
    }
    if ($days < 0) {
        $days += 28; // if we will finish with value under 0, just add 4 weeks
    }
    $calStart->setDate($selYear, 1, $days);
}

OTHER TIPS

If you're looking to get $calStart to start in the same year as $rangeEnd this should do it for you:

$calStart = new DateTime('2014-01-17');
if ($selYear !== $calStart->format('Y')) {
    $calStart->setDate($selYear , $calStart->format('n'), $calStart->format('j'));
}
$interval = DateInterval::createFromDateString('4 weeks');
$rangeEnd = new DateTime($selYear . '-12-31');
$rangeDays = new DatePeriod($calStart, $interval, $rangeEnd);

I'm not sure how you get 2015-01-16 as the new start date so I wasn't able to address that directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top