How to get second Tuesday of a given month or get third Thursday of a given month using moment js.
I tried finding a solution but was unsuccessful. I wrote it myself and posted the answer below and if you have a better solution u can answer your implementation.
Here an updated version of the answer I linked in the comments. I've use weekday
to use locale-aware day of the week, you can use day
if you always want Sunday as 0 and Saturday as 6.
var getGivenDateOfMonth = function (startDate, dayOfWeek, weekNumber) {
// Start of the month of the given startDate
var myMonth = moment(startDate).startOf('month');
// dayOfWeek of the first week of the month
var firstDayOfWeek = myMonth.clone().weekday(dayOfWeek);
// Check if first firstDayOfWeek is in the given month
if( firstDayOfWeek.month() != myMonth.month() ){
weekNumber++;
}
// Return result
return firstDayOfWeek.add(weekNumber-1, 'weeks');
}
// Examples
var secondMondayOfJuly = getGivenDateOfMonth('2017-07-10', 1, 2);
console.log(secondMondayOfJuly.format());
var thirdFridayOfJuly = getGivenDateOfMonth('2017-07-10', 5, 3);
console.log(thirdFridayOfJuly.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With