moment.js, how to get day of week number

DateMomentjs

Date Problem Overview


I have a moment date object, and want to get the selected day number (0-6) or (1-7).

I tried this, but it doesn't work

var aaa = moment(date).day();

help me with this please

Date Solutions


Solution 1 - Date

Define "doesn't work".

const date = moment("2015-07-02"); // Thursday Feb 2015
const dow = date.day();
console.log(dow);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

This prints "4", as expected.

Solution 2 - Date

If you are specifically looking for the 1-7 approach...

This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()

console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Seeing as I wrote this answer on a Tuesday, today this gives me a 2.

Solution 3 - Date

I think this would work

moment().weekday(); //if today is thursday it will return 4

Solution 4 - Date

You can get this in 2 way using moment and also using Javascript

const date = moment("2015-07-02"); // Thursday Feb 2015
const usingMoment_1 = date.day();
const usingMoment_2 = date.isoWeekday();

console.log('usingMoment: date.day() ==> ',usingMoment_1);
console.log('usingMoment: date.isoWeekday() ==> ',usingMoment_2);


const usingJS= new Date("2015-07-02").getDay();
console.log('usingJavaSript: new Date("2015-07-02").getDay() ===> ',usingJS);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Solution 5 - Date

From the docs page, notice they have these helpful headers

http://momentjs.com/docs/#/get-set/weekday/
(I didn't see them at first)

With header sections for:

  • Date of Month
  • Day of Week
  • etc

.

  var now = moment();
  var day  = now.day();
  var date = now.date(); // Number

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDevView Question on Stackoverflow
Solution 1 - Datec0xcView Answer on Stackoverflow
Solution 2 - DatemejdevView Answer on Stackoverflow
Solution 3 - DateTarun GuptaView Answer on Stackoverflow
Solution 4 - DateSaurabh MistryView Answer on Stackoverflow
Solution 5 - DateGene BoView Answer on Stackoverflow