moment.js, how to get day of week number
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
Solution 1:
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:
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:
I think this would work
moment().weekday(); //if today is thursday it will return 4
Solution 4:
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:
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