Java 获取当前财政年度的开始日期
在英国,纳税年度为每年4月6日至4月5日。我想获取当前纳税年度的开始日期(作为Java 获取当前财政年度的开始日期,java,localdate,java-time,Java,Localdate,Java Time,在英国,纳税年度为每年4月6日至4月5日。我想获取当前纳税年度的开始日期(作为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 { r
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;
}
这非常简洁和简单。请注意,它不使用当前日期,而是接受一个日期。这使得测试更加容易。当然,调用它并提供当前日期很容易。使用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();
}
}
在您的情况下,set cal.set(年份,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;
}
}
在您的情况下,设置校准设置(年份,11,31);//每年12月31日我真的不认为你的建议很复杂,我怀疑你能把它做得很短。在这种情况下,你不是更喜欢少年(1)而不是多年(-1)吗?