基于开始日期和结束日期如何使用PHP获得财务年度?

时间:2015-06-01 12:12:37

标签: php

财政年度从四月开始。例如:

$startDate='2014-11-25' // Start date
$endDate ='2015-05-29'  // End date

输出仅显示FY-14-15,但我想要FY-14-15,FY-15-16

function calcFY($startDate,$endDate) {

    $prefix = 'FY-';

    $ts1 = strtotime($startDate);
    $ts2 = strtotime($endDate);

    $year1 = date('Y', $ts1);
    $year2 = date('Y', $ts2);

    $month1 = date('m', $ts1);
    $month2 = date('m', $ts2);

    //get months
    $diff = (($year2 - $year1) * 12) + ($month2 - $month1);

    /**
     * if end month is greater than april, consider the next FY
     * else dont consider the next FY
     */
    $total_years = ($month2 > 4)?ceil($diff/12):floor($diff/12);

    $fy = array();

    while($total_years >= 0) {

        $prevyear = $year1 - 1;

        //We dont need 20 of 20** (like 2014)
        $fy[] = $prefix.substr($prevyear,-2).'-'.substr($year1,-2);

        $year1 += 1;

        $total_years--;
    }
    /**
     * If start month is greater than or equal to april, 
     * remove the first element
     */
    if($month1 >= 4) {
        unset($fy[0]);
    }
    /* Concatenate the array with ',' */
    return implode(',',$fy);
}

echo calcFY('2014-11-25','2015-05-29');

我的问题是,财政年度错过FY-15-16。我所尝试的并不是一个更好的代码来获得更多这么多年来说startdate =' 2014-11-25'和endDate =' 2015-05-29',

2 个答案:

答案 0 :(得分:0)

$diff返回1而不是2 - 您必须调整https://github.com/sstephenson/rbenv/blob/master/libexec/rbenv的计算。

答案 1 :(得分:0)

function calcFY($startDate, $endDate) {

$prefix = 'FY-';

$ts1 = strtotime($startDate);
$ts2 = strtotime($endDate);

$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);

$month1 = date('m', $ts1);
$month2 = date('m', $ts2);

$fy = array();
$idx = 0;

if((int)$month1<4)
{
    $fy[$idx] = $prefix . substr($year1-1, -2). '-'. substr($year1, -2);
    $idx++;
}

for($i = $year1; $i<=$year2; $i++)
{
    $fy[$idx] = $prefix . substr($i, -2).'-'.substr($i+1, -2);  $idx++; 
}

return implode(',',$fy);
}