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
You could use the remainder (
%
) operator to apply your offset:This is just a fancy way of doing an
if/else
based on the month were we subtract1
, unless the input is1
, then we set it to12
:So the final result, using the remainder operator, as a one-liner:
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
You can do this mathematically.