The moment().day() method in Moment.js returns or sets the day of the week for a moment object, where Sunday is represented as 0 and Saturday as 6. It helps manipulate and format weekday data easily in JavaScript.
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 momentExample 1: The below examples will demonstrate the Moment.js moment().day() Method.
const moment = require('moment');
// Print the current date and time
console.log("Current Date:", moment().toString())
// Get the current day of the week (0 for Sunday, 6 for Saturday)
console.log("Current day is:", moment().day())
// Set the date to this week's Wednesday (day 3)
let thisWeekWednesday = moment().day(3);
console.log(
"This week's Wednesday is:",
thisWeekWednesday.toString()
)
// Set the date to this week's Saturday (day 6)
let thisWeekSaturday = moment().day(6);
console.log(
"This week's Saturday is:",
thisWeekSaturday.toString()
)
// Set the date to this week's Monday (day 1)
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: The below examples will demonstrate the Moment.js moment().day() Method.
const moment = require('moment');
console.log("Current Date:", moment().toString())
console.log("Current day is:", moment().day())
// Set to next week's Wednesday (day 10)
let nextWeekWednesday = moment().day(10);
console.log("Next week's Wednesday is:", nextWeekWednesday.toString())
// Set to previous week's Wednesday (day -4)
let prevWeekWednesday = moment().day(-4);
console.log("Previous week's Wednesday is:", prevWeekWednesday.toString())
// Set to next week's Sunday (day 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