Open In App

How To Get Day of Week Number in Moment.js?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Moment.js is a popular and open-source JavaScript library for validating, manipulating, and formatting dates. One common task is to determine the day of the week for a given date. This can be particularly useful in applications that need to perform actions based on the day of the week. In this article,we will explore various approaches to get the day of the week number using Moment.js.

To use Moment.js, we must ensure that we have installed it. We can do so by using the following command.

Installing Moment.js in Node.js

npm i moment

There are two main approaches to get the day of the week number in Moment.js:

  • Using the .day() method
  • Using the .weekday() method

1. Using the day() Method

In this approach we are using day() method of Moment.js which returns the day of the week as a number, where Sunday is 0 and Saturday is 6. This method is based on the ISO weekday numbering system.

Syntax:

moment().day();

Example: This example uses day() method to get day of week number in moment.js

JavaScript
const moment = require('moment');

let date = moment('2024-07-26');
let dayNumber = date.day();
console.log(`The day of the week for 2024-07-26 is: ${dayNumber}`);

Output:

The day of the week for 2024-07-26 is: 5

2. Using the weekday() Method

In this approach we are using the weekday() method in Moment.js which is similar to the day() method but follows the locale-aware week setting. This means it can return different values based on the locale settings. By default, it considers Monday as 0 and Sunday as 6.

Syntax:

moment().weekday();

Example: This example uses weekday() method to get day of week number in moment.js

JavaScript
const moment = require('moment');

let date = moment('2024-07-22');
let weekdayNumber = date.weekday();
console.log(`The weekday number for 2024-07-26 is: ${weekdayNumber}`);

Output:

The weekday number for 2024-07-26 is: 1



Next Article

Similar Reads