首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP:用于获取我们所处的财政年度的可扩展功能

PHP:用于获取我们所处的财政年度的可扩展功能
EN

Code Review用户
提问于 2019-11-15 09:21:11
回答 2查看 79关注 0票数 1

我有下面的东西

代码语言:javascript
复制
private function yearMenu() {
    $m = date('m');
    $y = date('Y');

    if (($m>3 && $y==2019) || ($m<4 && $y==2020)){
        $menu = 1;
    }
    if (($m>3 && $y==2020) || ($m<4 && $y==2021)){
        $menu = 2;
    }
    if (($m>3 && $y==2021) || ($m<4 && $y==2022)){
        $menu = 3;
    }
    if (($m>3 && $y==2022) || ($m<4 && $y==2023)){
        $menu = 4;
    }
    if (($m>3 && $y==2023) || ($m<4 && $y==2024)){
        $menu = 5;
    }
    if (($m>3 && $y==2024) || ($m<4 && $y==2025)){
        $menu = 6;
    }

    return $menu;
}

此代码按预期工作,即我希望能够给每个财政年度一个基于2019-2020年的整数,该整数是值1的基数,并且每年都在增加。

我想知道是否有一种更简洁和可伸缩的方法来做到这一点?

谢谢

EN

回答 2

Code Review用户

发布于 2019-11-15 13:01:56

改进方法:

根据所提供的资料,关键功能的目的是“返回本年度的特定菜单号码”。因此,函数名将更具有描述性,名称为getFinYearMenuNumber

先决条件是:

  • 你的财政年度经过“四月至四月”月期。
  • 整个间隔有起始年份2019和结束年份2015。为了使函数更加统一,这些边界可以作为输入参数传递:函数getFinYearMenuNumber($yearFrom,$yearTo)。

当前方法的主要问题是,它不可避免地会执行5过多的if检查(它们至少可以是相互排斥的if ... else if ... else if ...)。

相反,我们只需执行两个后续检查:

  • 如果当前年份降到所需的间隔时间
  • 如果当前月份是起始月份(4月)之后或之前的月份

最后版本:

代码语言:javascript
复制
function getFinYearMenuNumber($yearFrom, $yearTo) {
    $curr_month = (int) date('m');    # current month number
    $curr_year = (int) date('Y');     # current year
    $curr_date = new DateTime();

    if ((new DateTime("$yearFrom-04")) <= $curr_date && $curr_date <= (new DateTime("$yearTo-04"))) {
        if ($curr_month > 3) {
            return $curr_year - $yearFrom + 1; 
        } else if ($curr_month < 4) {
            return $curr_year - $yearFrom; 
        }
    }

    return 0;
}

print_r(getFinYearMenuNumber(2019, 2025));
票数 1
EN

Code Review用户

发布于 2019-11-15 15:41:36

您的当前版本在很大程度上是一段固定的代码,正如您可以看到的,有大量的重复,其结果可以总结为

  • 基于2019-04-01是第一年的开始
  • 从每年的第四个月算起的一年。

此代码非常基于这个前提,取开始日期(此方法的一个可选参数--默认为当前日期)代码接受测试日期与2019-04-01日期之间的差异(使用diff())。这将返回DateInterval的一个实例,然后您可以提取年份组件(y)并添加1,以便2019年是第一年。

(更改为测试目的的独立功能).

代码语言:javascript
复制
function getFinanceYear ( DateTime $dateToTest = null)  {
    // Use date passed in, or default to current date
    $dateToTest = $dateToTest ?? new DateTime();
    // Calculate the difference
    $interval = $dateToTest->diff(new DateTime("2019-04-01"));
    // return the difference in years (offset by 1)
    return $interval->y+1;
}

几次测试..。

代码语言:javascript
复制
echo getFinanceYear().PHP_EOL;  // 1
echo getFinanceYear(new DateTime("2029-03-01")).PHP_EOL;   // 10
echo getFinanceYear(new DateTime("2029-04-01")).PHP_EOL;   // 11
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/232432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档