Reputation: 3327
I'm working on the calendar functionality in my project using moment.js, i want to get the date of second week of 'Sunday' for the given month. Please help me on this.
Upvotes: 0
Views: 1532
Reputation: 64657
You can use .day(n)
, and then just combine it with .startOf('month')
to do this.
This method can be used to set the day of the week, with Sunday as 0 and Saturday as 6.
If the value given is from 0 to 6, the resulting date will be within the current (Sunday-to-Saturday) week.
If the range is exceeded, it will bubble up to other weeks.
Demo:
const days = {
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
Sun: 7
}
const nthDayOfMonth = (monthMoment, day, weekNumber) => {
let m = monthMoment.clone()
.startOf('month') // go to the beginning of the month
.day(day)
if (m.month() !== monthMoment.month()) m.add(7, 'd');
return m.add(7 * (weekNumber - 1), 'd').format('dddd YYYY-MM-DD')
}
console.log({
firstSaturdayThisMonth: nthDayOfMonth(moment(), days.Sat, 1),
firstSundayThisMonth: nthDayOfMonth(moment(), days.Sun, 1),
firstMondayThisMonth: nthDayOfMonth(moment(), days.Mon, 1),
firstTuesdayThisMonth: nthDayOfMonth(moment(), days.Tue, 1),
firstWednesdayThisMonth: nthDayOfMonth(moment(), days.Wed, 1),
firstThursdayThisMonth: nthDayOfMonth(moment(), days.Thu, 1),
firstFridayThisMonth: nthDayOfMonth(moment(), days.Fri, 1),
secondSaturdayThisMonth: nthDayOfMonth(moment(), days.Sat, 2),
secondSundayThisMonth: nthDayOfMonth(moment(), days.Sun, 2),
secondMondayThisMonth: nthDayOfMonth(moment(), days.Mon, 2),
secondTuesdayThisMonth: nthDayOfMonth(moment(), days.Tue, 2),
secondWednesdayThisMonth: nthDayOfMonth(moment(), days.Wed, 2),
secondThursdayThisMonth: nthDayOfMonth(moment(), days.Thu, 2),
secondFridayThisMonth: nthDayOfMonth(moment(), days.Fri, 2),
secondTuedayMarch2020: nthDayOfMonth(moment('2020-03-15'), days.Tue, 2),
thirdFridayDecember1986: nthDayOfMonth(moment('1986-12-04'), days.Fri, 3)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Upvotes: 4