1
votes

I've searched a bit on stack and I've only found the number of quarters between 2 dates.

But I am looking for the list of quarters between 2 dates.

So firstly we get the quarter number for each date.

We are getting them by next rule:

  1. quarter - january, february, march.

  2. quarter - april, may, june,

  3. quarter - july, august, september,

  4. quarter - october, november, december.

For each date we get the number of quarter. This part I can resolve by my own. The second part is to get range of quarters between 2 of them.

For example:

1 date is 01.07.2017 - 3 quarter,
2 date is 01.04.2018 - 2 quarter.

The range between 2 and 3 should be [3,4,1].

Could anybody please provide the solution for that ?

2
what is a "querters"? Please read How to Ask, tour and minimal reproducible example to make this question better so we can helpBugFinder
@BugFinder I am sorry for misspelling. I meant the quarter numbers.Andrew
But what quarter numbers? dates dont have quarter numbersBugFinder
@BugFinder we can get 2 quarters by 2 different dates. And then get the list of quarters between them.Andrew
It would really help if you'd give very concrete examples for the first date and second date. Note that different systems might use different ideas of quarters - if you mean "January to March, April to June, July to September, October to December" it would be worth specifying that explicitly.Jon Skeet

2 Answers

2
votes

Try something like this:

public static IEnumerable<int> GetQuarters(DateTime from, DateTime to)
{
    if (to < from)
        throw new ArgumentException($"{to} cannot be smaller than {from}", nameof(to));

    DateTime date = from;
    int lastQuarter = -1;
    while (date <= to)
    {
        int currentQuarter = (date.Month + 2) / 3;
        if (currentQuarter != lastQuarter)
            yield return currentQuarter;
        date = date.AddDays(1);
        lastQuarter = currentQuarter;
    }
}

It should give you back {3,4,1} if you call it like this:

var q = GetQuarters(new DateTime(2019, 08, 03), new DateTime(2020, 01, 01));
0
votes

Try following :

            DateTime startDate = DateTime.Parse("2/10/17");
            DateTime endDate = DateTime.Now;

            DateTime previousQuarter = new DateTime(
                startDate.Year, (4 * (startDate.Month / 4)) + 1, 1);

            List<DateTime> quarters = new List<DateTime>();

            DateTime quarter = previousQuarter;
            while (quarter < endDate)
            {
                quarter = quarter.AddMonths(3);
                quarters.Add(quarter);
            }