Andrew
Andrew

Reputation: 621

How to get quarter numbers between 2 Dates. Between 2 and 1 -> 2341

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 ?

Upvotes: 1

Views: 636

Answers (2)

jdweng
jdweng

Reputation: 34421

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);
            }

Upvotes: 0

mm8
mm8

Reputation: 169200

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));

Upvotes: 2

Related Questions