antonio_mg antonio_mg - 23 days ago 7
C# Question

Get quarter number given two dates

I have the next list with date quarters:


  • 1 Jan-Mar

  • 2 Apr-Jun

  • 3 Jul-Sep

  • 4 Oct-Dec



User can select any of them and this will be set as the first quarter. Next, he provides a year an month and I have to calculate the quarter number of the given date. As I don't mind the days, this are always set to 1. So, for example, if user selects the quarter 3, enter year 2017 and month 02 (2017-02-01), the result must be 3 because Jul-Sep become the number 1 and thus Jan-Mar the number 3.

So far, I can calculate the quarter number for static quarters:

DateTime date = DateTime.Parse('2017-02-01');
int quarterNumber = ((date.Month - 1) / 3) + 1;


How can I modify this to get the correct quarter, no matter which is set as the first?

Answer
DateTime date = DateTime.Parse("2017-02-01");
int quarterNumber = ((12+(date.Month - 1)-((x-1)*3)) %12 / 3) + 1;

where x is the selected quarter number from the list (1,2,3,4)