Skip to content
Related Articles
Open in App
Not now

Related Articles

Moment.js moment().quarter() Method

Improve Article
Save Article
  • Last Updated : 18 Jul, 2022
Improve Article
Save Article

The moment().quarter() method is used to get or set the quarter of the Moment object. There are 4 quarters in a year, hence this method accepts a value from 1 to 4. A value outside of the range will bubble up the year of the Moment to the next or previous years.

Note: The day of Moment would stay the same when this method is used for setting the quarter.

Syntax:

moment().quarter( Number );

Parameters: This method accepts a single parameter as mentioned above and described below:

  • Number: It is the quarter that has to be set for the Moment object. it is an optional parameter.

Return Value: This method returns the current quarter of the Moment.

Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

The below examples will demonstrate the Moment.js moment().quarter() Method.

Example 1:

Javascript




const moment = require('moment');
  
console.log("Current Date:", moment().toString())
console.log("Current quarter is:", moment().quarter())
  
let quarter1 = moment().quarter(1);
console.log(
    "Moment with Quarter of 1 is:",
    quarter1.toString()
)
  
let quarter2 = moment().quarter(2);
console.log(
    "Moment with Quarter of 2 is:",
    quarter2.toString()
)
  
let quarter3 = moment().quarter(3);
console.log(
    "Moment with Quarter of 3 is:",
    quarter3.toString()
)
  
let quarter4 = moment().quarter(4);
console.log(
    "Moment with Quarter of 4 is:",
    quarter4.toString()
)


Output:

Current Date: Sat Jul 16 2022 23:52:58 GMT+0530
Current quarter is: 3
Moment with Quarter of 1 is: Sun Jan 16 2022 23:52:58 GMT+0530
Moment with Quarter of 2 is: Sat Apr 16 2022 23:52:58 GMT+0530
Moment with Quarter of 3 is: Sat Jul 16 2022 23:52:58 GMT+0530
Moment with Quarter of 4 is: Sun Oct 16 2022 23:52:58 GMT+0530

Example 2:

Javascript




const moment = require('moment');
  
console.log("Current Date:", moment().toString())
console.log("Current quarter is:", moment().quarter())
  
let quarterOutsideRange = moment().quarter(10);
console.log(
    "Moment with Quarter of 10 is:",
    quarterOutsideRange.toString()
)
  
let quarterOutsideRangeNegative = moment().quarter(-2);
console.log(
    "Moment with Quarter of -2 is:",
    quarterOutsideRangeNegative.toString()
)


Output:

Current Date: Sat Jul 16 2022 23:52:58 GMT+0530
Current quarter is: 3
Moment with Quarter of 10 is: Tue Apr 16 2024 23:52:58 GMT+0530
Moment with Quarter of -2 is: Fri Apr 16 2021 23:52:58 GMT+0530

Reference: https://momentjs.com/docs/#/get-set/quarter/


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!