首页 > 解决方案 > 获取当前财政年度的开始日期

问题描述

在英国,纳税年度为每年的 4 月 6 日至 4 月 5 日。我想获取当前纳税年度的开始日期(作为 a LocalDate),例如,如果今天是 2020 年 4 月 3 日,则返回 2019 年 4 月 6 日,如果今天是 2020 年 4 月 8 日,则返回 2020 年 4 月 6 日。

我可以使用如下逻辑来计算它:

date = a new LocalDate of 6 April with today's year
if (the date is after today) {
    return date minus 1 year
} else {
    return date
}

但是有没有一些我可以使用的方法不那么复杂并且使用更简洁,也许是功能性的风格?

标签: javalocaldatejava-time

解决方案


有几种不同的方法,但很容易以漂亮的功能风格实现您已经指定的逻辑:

private static final MonthDay FINANCIAL_START = MonthDay.of(4, 6);

private static LocalDate getStartOfFinancialYear(LocalDate date) {
    // Try "the same year as the date we've been given"
    LocalDate candidate = date.with(FINANCIAL_START);
    // If we haven't reached that yet, subtract a year. Otherwise, use it.
    return candidate.isAfter(date) ? candidate.minusYears(1) : candidate;
}

这非常简洁明了。请注意,它使用当前日期 - 它接受一个日期。这使得测试变得更加容易。当然,调用它并提供当前日期很容易。


推荐阅读