Moment.js moment().day() Method
The moment().day() method is used to get or set the day of week of the Moment object. The day of the week can have a value between 0 and 6, where 0 denotes Sunday and 6 denotes Saturday. A value outside this range will make it go to the previous or upcoming weeks. This is not a locale-aware method, hence the dates will always be the same for the values.
Syntax:
moment().weekday( Number );
Parameters: This method accepts a single parameter as mentioned above and described below:
- Number: It is the day of the week that has to be set for the Moment object. it is an optional parameter.
Return Value: This method returns the current day of the week 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().day() Method.
Example 1:
Javascript
const moment = require( 'moment' ); console.log( "Current Date:" , moment().toString()) console.log( "Current day is:" , moment().day()) let thisWeekWednesday = moment().day(3); console.log( "This week's Wednesday is:" , thisWeekWednesday.toString() ) let thisWeekSaturday = moment().day(6); console.log( "This week's Saturday is:" , thisWeekSaturday.toString() ) let thisWeekMonday = moment().day(1); console.log( "This week's Monday is:" , thisWeekMonday.toString() ) |
Output:
Current Date: Mon Jul 18 2022 01:21:54 GMT+0530
Current day is: 1
This week’s Wednesday is: Wed Jul 20 2022 01:21:54 GMT+0530
This week’s Saturday is: Sat Jul 23 2022 01:21:54 GMT+0530
This week’s Monday is: Mon Jul 18 2022 01:21:54 GMT+0530
Example 2:
Javascript
const moment = require( 'moment' ); console.log( "Current Date:" , moment().toString()) console.log( "Current day is:" , moment().day()) // Next week is 7 (full week) + 3 (for Wednesday) = 10 let nextWeekWednesday = moment().day(10); console.log( "Next week's Wednesday is:" , nextWeekWednesday.toString() ) // Previous week is 3 (for Wednesday) - 7 (full week) = -4 let prevWeekWednesday = moment().day(-4); console.log( "Previous week's Wednesday is:" , prevWeekWednesday.toString() ) // Next week is 7 (full week) + 7 (for sunday) = 14 let nextWeekSunday = moment().day(14); console.log( "Next week's Sunday is:" , nextWeekSunday.toString() ) |
Output:
Current Date: Mon Jul 18 2022 01:21:54 GMT+0530
Current day is: 1
Next week’s Wednesday is: Wed Jul 27 2022 01:21:54 GMT+0530
Previous week’s Wednesday is: Wed Jul 13 2022 01:21:54 GMT+0530
Next week’s Sunday is: Sun Jul 31 2022 01:21:54 GMT+0530
Reference: https://momentjs.com/docs/#/get-set/day/
Please Login to comment...