DodgyCodeException
DodgyCodeException

Reputation: 6123

Get start date of current financial year

Here in the UK, the tax year runs from 6 April to 5 April each year. I want to get the start date of the current tax year (as a LocalDate), so for example if today is 3 April 2020, then return 6 April 2019, and if today is 8 April 2020, then return 6 April 2020.

I can calculate it using some logic like the following:

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
}

But is there some method I can use that is less complex and uses a more succinct, perhaps functional style?

Upvotes: 3

Views: 4201

Answers (2)

preetesh gurjar
preetesh gurjar

Reputation: 149

using java.util.Calendar, you can get financial year's START and END date in which your given date lies.

In India financial year starts from from 1 April and ends on 31st March, for financial year 2020-21 , dates will be 1 April 2020

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

In your case set cal.set(year, 0, 1); // 1 Jan of Year

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

In your case set cal.set(year, 11, 31); // 31 Dec of Year

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1502086

There are a few different approaches, but it's easy enough to implement the logic you've already specified in a pretty functional style:

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

That's pretty concise and simple. Note that it doesn't use the current date - it accepts a date instead. That makes it much easier to test. It's easy enough to call this and provide the current date, of course.

Upvotes: 15

Related Questions