How do I discover the quarter of a given date
The following are the Quarters for a financial year
April to June - Q1
July to Sep - Q2
Oct to Dec - Q3
Jan to March - Q4
If the month of an input date lies as above I need the output for in terms of Quarter number.
For Example,
If I give an input date (say january 2nd) , I need the output as Q4
.
If I give input as (Jun 5), output should give Q1
.
Based on input date I need the Quarter number.
If you prefer short and concise solutions without branching and arrays, here is my preferred solution.
Normal Quarter:
public static int GetQuarter(this DateTime date)
{
return (date.Month + 2)/3;
}
Financial Year Quarter:
public static int GetFinancialQuarter(this DateTime date)
{
return (date.AddMonths(-3).Month + 2)/3;
}
Integer division will truncate decimals, giving you an integer result. Place methods into a static class and you will have an extension method to be used as follows:
date.GetQuarter()
date.GetFinancialQuarter()
See dotnetfiddle
You can simply write an extension method to DateTime
public static int GetQuarter(this DateTime date)
{
if (date.Month >= 4 && date.Month <= 6)
return 1;
else if (date.Month >= 7 && date.Month <= 9)
return 2;
else if (date.Month >= 10 && date.Month <= 12)
return 3;
else
return 4;
}
and use it as
DateTime dt = DateTime.Now;
dt.GetQuarter();
This is for the "normal year". I think you can adapt the sample:
string.Format("Q{0}", (date.Month + 2)/3);
The most simple and consistent way of achieving this:
Regular
Math.Ceiling(date.Month / 3.0)
Fiscal (just shifted up with a mod by 2+1 quarters)
Math.Ceiling(date.Month / 3.0 + 2) % 4 + 1
01.01.2016 00:00:00 -> Q1 -> FQ4
01.02.2016 00:00:00 -> Q1 -> FQ4
01.03.2016 00:00:00 -> Q1 -> FQ4
01.04.2016 00:00:00 -> Q2 -> FQ1
01.05.2016 00:00:00 -> Q2 -> FQ1
01.06.2016 00:00:00 -> Q2 -> FQ1
01.07.2016 00:00:00 -> Q3 -> FQ2
01.08.2016 00:00:00 -> Q3 -> FQ2
01.09.2016 00:00:00 -> Q3 -> FQ2
01.10.2016 00:00:00 -> Q4 -> FQ3
01.11.2016 00:00:00 -> Q4 -> FQ3
01.12.2016 00:00:00 -> Q4 -> FQ3
Result is a value between 1 and 4. Nearly any environment has a CEIL function, so this should work on any language as well.
public static int GetQuarter(DateTime date)
{
int[] quarters = new int[] { 4,4,4,1,1,1,2,2,2,3,3,3 };
return quarters[date.Month-1];
}