tags:

views:

835

answers:

2

How can I find the start-date and name (1, 2, 3, etc.) of a quarter from a given date?

+8  A: 

Something like (untested):

DateTime date;
int quarterNumber = (date.Month-1)/3+1;
DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber-1)*3+1,1);
DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);
Joe
Can you explain what your code does?
roosteronacid
@roosteronacid: `(quarterNumber-1)*3+1` will give the month number of the first month of the given quarter. The code creates a `DateTime` for the first day of that month of the year. That is the first day of the quarter. Then it adds three months. That will be the first day of the *next* quarter, so the last day of the wanted quarter will be the day before that (`.AddDays(-1)` does that trick).
Fredrik Mörk
+1  A: 
int GetQuarterName(DateTime myDate)
{
    return Math.Ceiling(myDate.Month / 3);
}

DateTime GetQuarterStartingDate(DateTime myDate)
{
    return new DateTime(myDate.Year,(3*GetQuarterName(myDate))-2,1);
}

GetQuarterName gets the "next" integer value of the current month number / 3.

GetQuarterStartingDate uses the output from GetQuarterName to work out the month value, the year part of the original date, and 1 to represent the first day of the month to return.

(Apologies for making no sense, I have flu. :( )

ZombieSheep