skip to Main Content

How do I get a quarter number if the quarter starts in February?

Quarter 1: Feb – April

Quarter 2: May – July

Quarter 3: August – October

Quarter 4: November – January

The following won’t work because of the overlap November – January for quarter 4. I have also tried incrementing, subtracting month or total by 1. Not sure which way I should go.

const month = 1; // January = 1

function getQuarter(month) {
  return Math.ceil(month / 3);
}

Expected result

getQuarter(1);  // 4
getQuarter(11); // 4
getQuarter(12); // 4
getQuarter(2);  // 1
getQuarter(5);  // 2
getQuarter(8);  // 3

3

Answers


  1. You could use the remainder (%) operator to apply your offset:

    ((month + 10) % 12) + 1
    

    This is just a fancy way of doing an if/else based on the month were we subtract 1, unless the input is 1, then we set it to 12:

    let customMonth = (month === 1) ? 12 : (month - 1);
    

    So the final result, using the remainder operator, as a one-liner:

    function getQuarter(month) {
        return Math.ceil((((month + 10) % 12) + 1) / 3);
    }
    
    for (let i = 1; i <= 12; i++) {
        console.log(`${i} -> ${getQuarter(i)}`);
    }
    Login or Signup to reply.
  2. Since your first quarter start in february you need to minus 1 the month and handle the january month as a special case and just return 4

    You can also handle if invalid number given

    function getQuarter(month) {
      if (month < 1 || month > 12) return null
    
      if (month === 1) return 4
    
      return Math.ceil((month - 1) / 3);
    }
    
    console.log(getQuarter(0), null)
    console.log(getQuarter(1), 4) // January
    console.log(getQuarter(2), 1) // February
    console.log(getQuarter(3), 1) // March
    console.log(getQuarter(4), 1) // April
    console.log(getQuarter(5), 2) // May
    console.log(getQuarter(6), 2) // June
    console.log(getQuarter(7), 2) // July
    console.log(getQuarter(8), 3) // August
    console.log(getQuarter(9), 3) // September
    console.log(getQuarter(10), 3) // October
    console.log(getQuarter(11), 4) // November
    console.log(getQuarter(12), 4) // December
    console.log(getQuarter(13), null)
    <pre>
    Quarter 1: Feb - April
    
    Quarter 2: May - July
    
    Quarter 3: August - October
    
    Quarter 4: November - January
    </pre>
    Login or Signup to reply.
  3. You can do this mathematically.

    function getQuarter(month) {
      
      // Rotate month values so that February starts at zero
      month = (month + 10) % 12;
      
      // Find the zero-based quarter: Feb to Apr => 0, May to Jun => 1, etc.
      quarter = Math.floor(month / 3);
       
      // Add 1 so that q0 to q3 is returned as q1 to q4.
      return quarter + 1;
    }
    
    for (let month = 1; month <= 12; month++)
      console.log(`Month: ${month} - Quarter: ${getQuarter(month)}`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search