Suppose the current quater is 3 and the year is 2011. How can I get the last 5 quarters
Desired output:
Q3-2011
Q2-2011
Q1-2011
Q4-2010
Q3-2010
The Q and '-' is appended.
I am trying as under
int generateQuater = 5;
int currentQuater = 3;//GetQuarter(DateTime.Now.Month);
int currentYear = DateTime.Now.Year;
List<string> lstQuaterYear = new List<string>();
lstQuaterYear.Add(string.Concat('Q',currentQuater, '-', currentYear));
for (int i = generateQuater; i > 0; i++)
{
//code to be placed
}
Thanks
Don't forget to refactor it :)
You have to decrease your loop variable. The rest is not too difficult math. Its also not necessary to handle the first iteration in any special way:
As a pure LINQ expression:
The math is somewhat ugly but does work, to use it you can just do:
One way is to check for year roll over and then set the quarter to 4 and decrement the year:
Alternatively you could calculate a
totalQuartal=year+quartal-1
. Then decrement it on each step. And finally useyear=totalQuartal/4
andquartal=totalQuartal%4+1
. But I think the first way is easier to understand.In case you should do some operations on the quarter period, like check if moment is within a quarter, you can use the Quarter class of the Time Period Library for .NET: