Moment js get specific day of month by week and day of the week
3 answers
//get a preferred day of a month
var getGivenDateOfMonth = function (startDate, dayOfWeek, weekNumber) {
var startOfMonth = moment(startDate).utc().startOf('month').startOf('isoweek');
var dayOne = moment((moment(startDate, "YYYY-MM-DD").format("YYYY-MM") + "-01"),"YYYY-MM-DD");
var studyDate;
if (dayOne.isoWeekday() === 1) {
studyDate = moment(startDate).utc().startOf('month').startOf('isoweek').add(dayOfWeek - 1, 'days')
.add(weekNumber, 'w');
}
else if (dayOne.isoWeekday() <= dayOfWeek) {
studyDate = moment(startDate).utc().startOf('month').startOf('isoweek').add(dayOfWeek - 1, 'days')
.add(weekNumber - 1, 'w');
} else {
studyDate = moment(startDate).utc().startOf('month').startOf('isoweek').add(dayOfWeek - 1, 'days')
.add(weekNumber, 'w');
}
if (studyDate.month() == startOfMonth.month()) {
studyDate = studyDate.subtract(1, 'w');
}
return studyDate;
};
startDate is the date in the given month.
dayOfWeek is the day of the js ISO of the day of the week and
weeknumber is the week number (1,2,3,4) you want
+2
source to share
Here is an updated version of the answer that I linked in the comments. I am using weekday
to use the significant day of the week, you can use day
if you always want Sunday to be 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>
+2
source to share
function nthDayOfMonth(month, year, day, weekNum){
var nearestDay = moment(month + " " + year,"M YYYY").day(day);
var nthDay = nearestDay.add(nearestDay.isSame(moment({month: month}),"month") ? weekNum - 1 : weekNum ,"weeks");
return nthDay;
}
document.write(nthDayOfMonth(7,2017,3,3).format("L"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
0
source to share