Get last 'N' quarters in C#

2020-03-18 04:11发布

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

标签: c#
8条回答
爷、活的狠高调
2楼-- · 2020-03-18 04:48

Here is my version (sorry, it is in VB.NET).

The idea is to :

  • easily find out the quarter based on a date (easy : divide it by 4 ... and add 1 to avoid zeros)
  • go back in time from the current date, removing 3 month at each time
  • printout the formatted quarter

the code :

Private Shared Function GetQuarterForDate(ByVal d As DateTime) As Integer
    Return (d.Month \ 4) + 1 'integer division
End Function

Private Shared Function GetLastNQuarters(ByVal N As Integer) As IEnumerable(Of String)
    Dim myDate = DateTime.Now
    Dim res As New List(Of String)()
    Do While N > 0
        'using yield would be nicer in C# ... does not exist in VB
        res.Add(String.Format("Q{0}-{1}", GetQuarterForDate(myDate), myDate.Year))
        myDate = myDate.AddMonths(-3)
        N = N - 1
    Loop
    Return res
End Function

<TestMethod()>
Public Sub CanRetrieveQuarter()
    Dim quarters = GetLastNQuarters(5)

    For Each q In quarters
        Console.WriteLine(q)
    Next
End Sub

That last "test method" prints out :

Q3-2011
Q2-2011
Q1-2011
Q4-2010
Q3-2010
查看更多
乱世女痞
3楼-- · 2020-03-18 04:49

Your for loop should go from 0 to your variable, when you're increasing i.

The inner code could be something like:

currentQuarter--;
if(currentQuarter == 0)
{
  currentQuarter = 4;
  currentYear--;
}
查看更多
登录 后发表回答