获取当前财政年度的开始日期

时间:2019-07-24 14:01:45

标签: java localdate java.time

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

我可以使用类似以下的逻辑来计算它:

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
}

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

2 个答案:

答案 0 :(得分:8)

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

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;
}

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

答案 1 :(得分:-1)

使用 java.util.Calendar,您可以获得指定日期所在的财政年度的开始和结束日期。

在印度,财政年度从 4 月 1 日开始,到 3 月 31 日结束, 对于 2020-21 财政年度,日期为 2020 年 4 月 1 日

 public static Date getFirstDateOfFinancialYear(Date dateToCheck) {
            int year = getYear(dateToCheck);
            Calendar cal = Calendar.getInstance();
            cal.set(year, 3, 1); // 1 April of Year
            Date firstAprilOfYear = cal.getTime();
    
            if (dateToCheck.after(firstAprilOfYear)) {
                return firstAprilOfYear;
            } else {
                cal.set(year - 1, 3, 1);
                return cal.getTime();
            }
        }

在你的情况下设置 cal.set(year, 0, 1); // 1 月 1 日

public static Date getLastDateOfFinancialYear(Date dateToCheck) {
            int year = getYear(dateToCheck);
            Calendar cal = Calendar.getInstance();
            cal.set(year, 2, 31); // 31 March of Year
            Date thirtyFirstOfYear = cal.getTime();
    
            if (dateToCheck.after(thirtyFirstOfYear)) {
                cal.set(year + 1, 2, 31);
                return cal.getTime();
            } else {
                return thirtyFirstOfYear;
            }
        }

在你的情况下设置 cal.set(year, 11, 31); // 每年 12 月 31 日