Open In App

Moment.js moment().dayOfYear() Method

Last Updated : 18 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().dayOfYear() method is used to get or set the day of the year of the Moment object. This can be a value between 1 and 366 denoting the first and last possible day of the year. A value outside of this range will set the day for the previous or next years.

Syntax:

moment().dayOfYear( Number );

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

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

Return Value: This method returns the day of the year 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().dayOfYear() Method.

Example 1:

Javascript




const moment = require('moment');
  
console.log("Current dayOfYear:", moment().toString())
console.log("Current dayOfYear is:", moment().dayOfYear())
  
let dayOfYear1 = moment().dayOfYear(1);
console.log(
    "Moment with dayOfYear of 1 is:",
    dayOfYear1.toString()
)
  
let dayOfYear365 = moment().dayOfYear(365);
console.log(
    "Moment with dayOfYear of 365 is:",
    dayOfYear365.toString()
)
  
let dayOfYear181 = moment().dayOfYear(180);
console.log(
    "Moment with dayOfYear of 181 is:",
    dayOfYear181.toString()
)


Output:

Current dayOfYear: Mon Jul 18 2022 01:58:29 GMT+0530
Current dayOfYear is: 199
Moment with dayOfYear of 1 is: Sat Jan 01 2022 01:58:29 GMT+0530
Moment with dayOfYear of 365 is: Sat Dec 31 2022 01:58:29 GMT+0530
Moment with dayOfYear of 181 is: Wed Jun 29 2022 01:58:29 GMT+0530

Example 2:

Javascript




const moment = require('moment');
  
let momentX = moment().year(2008).dayOfYear(30);
  
console.log("momentX dayOfYear:", momentX.toString())
console.log("momentX dayOfYear is:", momentX.dayOfYear())
  
// This will set the date for the next year
let dayOfYear450 = momentX.dayOfYear(450);
console.log(
    "momentX with dayOfYear of 450 is:",
    dayOfYear450.toString()
)
  
// This will set the date to 2 year's before
let negativeDayOfYear800 = momentX.dayOfYear(-800);
console.log(
    "momentX with dayOfYear of -800 is:"
    negativeDayOfYear800.toString()
)


Output:

momentX dayOfYear: Wed Jan 30 2008 01:58:29 GMT+0530
momentX dayOfYear is: 30
momentX with dayOfYear of 450 is: Wed Mar 25 2009 01:58:29 GMT+0530
momentX with dayOfYear of -800 is: Mon Oct 23 2006 01:58:29 GMT+0530

Reference: https://momentjs.com/docs/#/get-set/day-of-year/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads