日期范围之间的活动日计数

时间:2017-01-19 12:38:50

标签: php date-range calculation

我在日期计算方面遇到了一些麻烦。我将尝试尽可能多地解释它;

我们假设你有一个广告牌,这个媒体有活跃的日期范围。例如,活动期限的开始时间为每年的12月1日,活动期限的结束时间为每年的3月1日。

请考虑您在特定时间段内将此广告牌租给某人。示例日期范围是2017年2月1日到2020年12月10日。在此期间,我如何计算可结算日期计数?尝试用PHP做但是坚持。任何人都可以帮助我做到这一点而不会有太多的"如果"条款?

编辑:

    $activeTermStart = "01/12"; // 'd/m'
    $activeTermEnd = "01/03"; // 'd/m'

    $daterangeStart = new \DateTime('2017-02-01');
    $daterangeEnd = new \DateTime('2020-12-10');

    //check if active term start&end have year diff
    $hasYearDiffBetweenTermStartAndEnd = false;

    $startArray = explode('/',$activeTermStart);
    $endArray = explode('/',$activeTermEnd);
    if ($startArray[1]>$endArray[1]) {
        $hasYearDiffBetweenTermStartAndEnd = true;
    }
    if ($startArray[1]==$endArray[1] && $startArray[0]>=$endArray[0]) {
        $hasYearDiffBetweenTermStartAndEnd = true;
    }

    $startTermWithYear = \DateTime::createFromFormat('d/m/Y',$activeTermStart.'/'.date('Y'));
    $startTermWithFirstYear = \DateTime::createFromFormat('d/m/Y',$activeTermStart.'/'.$daterangeStart->format('Y'));
    if ($hasYearDiffBetweenTermStartAndEnd) {
        $endTermWithYear = \DateTime::createFromFormat('d/m/Y',$activeTermEnd.'/'.(date('Y')+1));
        $endTermWithFirstYear = \DateTime::createFromFormat('d/m/Y',$activeTermEnd.'/'.((int)$daterangeStart->format('Y')+1);
    } else {
        $endTermWithYear = \DateTime::createFromFormat('d/m/Y',$activeTermEnd.'/'.date('Y'));
        $endTermWithFirstYear = \DateTime::createFromFormat('d/m/Y',$activeTermEnd.'/'.$daterangeStart->format('Y'));
    }

    $maximumBillableDaysPerYear = ($endTermWithYear->getTimestamp() - $startTermWithYear->getTimestamp())/60/60/24;

    $totalYearsToCheck = ((int)$daterangeEnd->format('Y') - (int)$daterangeStart->format('Y'))+1;

    $maximumBillableDaysTotal = $totalYearsToCheck *  $maximumBillableDaysPerYear;

    // from that moment on, i want to see how many days are not in the first year and
    // how many days are not in the last year. Remove them from the maximumBillableDaysTotal to
    // see how many days that billboard is billable for.
    // stucked here...

0 个答案:

没有答案