How to discover financial Year based on current datetime?
A couple of Extension methods
public static class DateTimeExtensions
{
public static string ToFinancialYear(this DateTime dateTime)
{
return "Financial Year " + (dateTime.Month >= 4 ? dateTime.Year + 1 : dateTime.Year);
}
public static string ToFinancialYearShort(this DateTime dateTime)
{
return "FY" + (dateTime.Month >= 4 ? dateTime.AddYears(1).ToString("yy") : dateTime.ToString("yy"));
}
}
I've done the before by creating a FinancialYear
class:
public class FinancialYear
{
int yearNumber;
private static readonly int firstMonthInYear = 4;
public static FinancialYear Current
{
get { return new FinancialYear(DateTime.Today); }
}
public FinancialYear(DateTime forDate)
{
if (forDate.Month < firstMonthInYear) {
yearNumber = forDate.Year + 1;
}
else {
yearNumber = forDate.Year;
}
}
public override string ToString() {
return yearNumber.ToString();
}
}
Other points:
- Have a look at IFormatProvider to see how you can customize formatting (you could provide an overload of ToString that takes a format argument like DateTime does.
- override Equals, and implement IEquitable to provide equality.
- Implement IComparable to give comarisons.
- You could also implement your own == < > >= and <= operators for the class.