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 = SomeFunction(jan 3, 2010);
would set lastDayOfLastQuarter = Dec 31, 2009
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 = SomeFunction(jan 3, 2010);
would set lastDayOfLastQuarter = Dec 31, 2009
Try this:
The AddMonths(-(d.Month-1) % 3))
moves the datevalue to the equivilent day of the first month in the quarter, and then the AddDays (-day)
moves back to the last day of the preceding month.
DateTime d = Datetime.Now;
DateTime lastDayOfLastQuarter = d.AddMonths(-((d.Month-1)%3)).AddDays(-d.Day);
public static DateTime NearestQuarterEnd(this DateTime date) {
IEnumerable<DateTime> candidates =
QuartersInYear(date.Year).Union(QuartersInYear(date.Year - 1));
return candidates.Where(d => d <= date).OrderBy(d => d).Last();
}
static IEnumerable<DateTime> QuartersInYear(int year) {
return new List<DateTime>() {
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.
Assuming quarters always end at 3 month intervals you could do:
Maybe not the best solution, but very easy to read and modify compared to other solutions offered.
public void LastDayOfLastQuarter(DateTime date)
{
int result = (int)(date.Month/3)
switch (result)
{
// January - March
case 0:
return new DateTime(date.Year - 1, 12, 31)
// April - June
case 1:
return new DateTime(date.Year, 3, 31)
// July - September
case 2:
return new DateTime(date.Year, 6, 30)
// October - December
case 3:
return new DateTime(date.Year, 9, 30)
}
}
Here's a simple function to give you the last day of the current quarter (assuming you're using a standard calendar).
DateTime LastDayOfQuarter(DateTime today)
{
int quarter = (today.Month-1) / 3;
int lastMonthInQuarter = (quarter +1) * 3;
int lastDayInMonth = DateTime.DaysInMonth(today.Year, lastMonthInQuarter);
return new DateTime(today.Year, lastMonthInQuarter, lastDayInMonth);
}
Hope that helps.
A simple function can calculate the last days of the most recently completed month:
public static DateTime LastQuarter(DateTime date)
{
return new DateTime(date.Year, date.Month - ((date.Month - 1) % 3), 1).AddDays(-1);
}