What Financial Year does a date fall in?
In fact, I needed to know the actual date range of the year, so my function looks slightly different, but not by much (comments omitted for brevity):
public void DateToFinancialYear2( DateTime dtIn, out DateTime dtStartOut, out DateTime dtEndOut ) { DateTime dtFYStart = new DateTime( dtIn.Year, financialYearEndMonth%12+1, 1 ); if( dtIn < dtFYStart ) { dtFYStart=dtFYStart.AddYears(-1); } dtStartOut = dtFYStart; dtEndOut = dtFYStart.AddYears(+1).AddDays(-1); } //DateToFinancialYear2
Now, If you have a FY definition that does not start on the first day of a month, but still starts on a defined day - say the 20th - then I’m sure you can work out how to extend these. It will be easier if the year is defined by its start date, and you might want some error checking in case someone defines the year as starting on the 29th of February, but the actual algorithm remains unchanged.
If your financial year is defined as, say, always ending on a Friday, then this algorithm doesn’t work. In that case the best route may well be to go for ultimate flexibility: define a table listing each financial year, and search to find the one the one you’re looking for. If I were building an accounting system from scratch, this is definitely the technique I’d plan on, and it’s the kind of thing that SQL is built for:
SELECT * FROM FinancialYear fy WHERE @date_in BETWEEN fy.start_date AND fy.end_date
Just to finish things off, I also had the need for a matching function to give the date range of the financial quarter. There probably is a fast mathematical way to do this, but brute force does the trick just fine:
public void DateToFinancialQuarter( DateTime dtIn, out DateTime dtStartOut, out DateTime dtEndOut ) { DateTime dtStart, dtEndMaybe; // get which financial year (not actually interested in the end date) DateToFinancialYear2( dtIn, out dtStart, out dtEndMaybe ); // So which quarter are we in? for( int ii = 0; ii < 4; ++ii ) { dtEndMaybe = dtStart.AddMonths(3); if( dtIn < dtEndMaybe ) { dtStartOut = dtStart; dtEndOut = dtEndMaybe.AddDays(-1); return; // from the FOR loop _and_ the method } dtStart = dtEndMaybe; } // We are GUARANTEED never to get here, right? throw new Exception( "Internal program error" ); } // DateToFinancialQuarter
I wrote a bit of a test suite for this, but it’s not really worth posting .. so I won’t.
Pages: 1 2