I'm using MomentJS and fullcalendar. I want to get the first Monday of a month. I tried the following code but it doesn't work.
let date = new Date(year, month, 1)
moment(date).isoWeekday(1)
I'm using MomentJS and fullcalendar. I want to get the first Monday of a month. I tried the following code but it doesn't work.
let date = new Date(year, month, 1)
moment(date).isoWeekday(1)
The following code have solved my problem:
let date = moment().set('year', y).set('month', m).set('date', 1).isoWeekday(8)
if(date.date() > 7) { //
date = date.isoWeekday(-6)
}
I believe @xenteros's answer doesn't work for months that begin on a Sunday, because Monday would be the 9th.
Here is a simple fix:
let date = moment().year(y).month(m).date(1).day(8);
if (date.date() > 7)
date.day(-6);
The following code have solved my problem:
let date = moment().set('year', y).set('month', m).set('date', 1).isoWeekday(8)
if(date.date() > 7) { //
date = date.isoWeekday(-6)
}
Here are the steps to get the first monday
Create a day (any day in that specific month)
Get the start of the month, this will return a date
There is two cases for first day, it could be Monday or not Monday
We add 6 days to the first day of the month, if it is Monday, we will get Sunday (same week), else we get a date in the next week that has a Monday (that occure in the same month)
calling startOf('isoWeek')
will return the first Monday of that month
let date = new Date(year, month, 1);
const firstMondayOfTheMonth = date
.startOf('month')
.add(6, 'day')
.startOf('isoWeek');
Use moment js. You can pass as parameter any year and month.
import moment from 'moment';
const startOfMonth = moment().year(2021).month(0).startOf('month').isoWeekday(8);
console.log(startOfMonth.format('dddd DD-MM-YYYY')); // Monday 04-01-2021
Month: 0-11.
© 2022 - 2024 — McMap. All rights reserved.
isoWeekday
makes you think it will give you the first Monday of the month? You need to do a bit more work than just setting the current Monday. Give it a try. If you get stuck, ask a specific question. – Polynesian