java - 获取当前财政年度的开始日期
问题描述
在英国,纳税年度为每年的 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
}
但是有没有一些我可以使用的方法不那么复杂并且使用更简洁,也许是功能性的风格?
解决方案
有几种不同的方法,但很容易以漂亮的功能风格实现您已经指定的逻辑:
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;
}
这非常简洁明了。请注意,它不使用当前日期 - 它接受一个日期。这使得测试变得更加容易。当然,调用它并提供当前日期很容易。
推荐阅读
- typescript - TypeScript 中的符号意义
- ios - OTP 屏幕设计 - 如何使 texField 不可点击以进行编辑,但只有在最后一个 textField 完成后才能变为活动状态?
- azure-active-directory - Azure Active Directory 企业应用程序中的 Office 365 管理 API
- javascript - JavaScript 正则表达式字符串拆分
- javascript - 关于在时钟输出网络应用程序中构建时钟的任何指针
- ios - iOS中的2向滚动表
- angular - 在 Angular6 中使用 Observables 更改参数的 Api 服务
- c# - 当客户端设置事件侦听器时,进程 COM 服务器崩溃
- orientdb - 如何插入地图
> 在东方数据库 - websocket - 如何在没有 Python 的情况下生成本地 SDP