Is there a C# function which will give me the last day of the most recently finished Quarter given a date?
For example,
var lastDayOfLastQuarter = So
public static DateTime NearestQuarterEnd(this DateTime date) {
IEnumerable candidates =
QuartersInYear(date.Year).Union(QuartersInYear(date.Year - 1));
return candidates.Where(d => d < date.Date).OrderBy(d => d).Last();
}
static IEnumerable QuartersInYear(int year) {
return new List() {
new DateTime(year, 3, 31),
new DateTime(year, 6, 30),
new DateTime(year, 9, 30),
new DateTime(year, 12, 31),
};
}
Usage:
DateTime date = new DateTime(2010, 1, 3);
DateTime quarterEnd = date.NearestQuarterEnd();
This method has the advantage in that if you have an odd definition of quarters (for example, fiscal year is different than calendar year) the method QuartersInYear is easily modified to handle this.