Horje
JavaScript: Check the Month is in Which Quarter?

When working with dates in JavaScript, it’s often useful to determine which quarter a particular month falls into. Knowing the quarter can aid in various date-related calculations or visual representations. In this article, we will explore different approaches to check the month and it’s quarter using JavaScript.

These are the following approaches:

Using Math operations

In this approach, we divide the month number by 3 and use the Math.ceil() function to round up to the nearest integer. This effectively groups the months into quarters.

Example: This example uses math operations to check the quarter of month.

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

console.log(getQuarter(5));

Output
2

Using a switch statement

In this approach, we use a switch statement to handle each quarter based on the result of dividing the month number by 3. Each case corresponds to a quarter and we return the appropriate quarter based on the input month.

Example: This example uses switch statement to check the quarter of month.

JavaScript
function getQuarter(month) {
    switch (Math.ceil(month / 3)) {
        case 1:
            return "First Quarter";
        case 2:
            return "Second Quarter";
        case 3:
            return "Third Quarter";
        case 4:
            return "Fourth Quarter";
        default:
            return "Invalid month";
    }
}

console.log(getQuarter(9)); 

Output
Third Quarter



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Draw on Scroll using JavaScript and SVG ? How to Draw on Scroll using JavaScript and SVG ?
Synchronous and Asynchronous Programming Synchronous and Asynchronous Programming
JavaScript TypedArray.prototype.toSorted() Method JavaScript TypedArray.prototype.toSorted() Method
How to Make Auto Scrolling with CSS? How to Make Auto Scrolling with CSS?
How to Create a Fixed/Sticky Header on Scroll with CSS and JavaScript? How to Create a Fixed/Sticky Header on Scroll with CSS and JavaScript?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14