Given a year and month, I'd like to determine the date of the third Friday of that month. How would I leverage moment.js to determine this?
E.g. October 2015 => 16th October 2015
Given a year and month, I'd like to determine the date of the third Friday of that month. How would I leverage moment.js to determine this?
E.g. October 2015 => 16th October 2015
Given year and month as integers and assuming that Friday is the fifth day of the week in your locale (Monday is the first day of the week), you can have:
function getThirdFriday(year, month){
// Convert date to moment (month 0-11)
var myMonth = moment({year: year, month: month});
// Get first Friday of the first week of the month
var firstFriday = myMonth.weekday(4);
var nWeeks = 2;
// Check if first Friday is in the given month
if( firstFriday.month() != month ){
nWeeks++;
}
// Return 3rd Friday of the month formatted (custom format)
return firstFriday.add(nWeeks, 'weeks').format("DD MMMM YYYY");
}
If you have month and year as a string, you can use moment parsing functions instead of the Object notation, so you will have:
var myMonth = moment("October 2015", "MMMM yyyy");
If Friday is not the fifth day of the week (day with index 4), you can get the correct index using moment.weekdays()
Based on on answers above (1 and 2),
I generalised the function so it can return any weekday or any week for any given date.
var getNthWeekday = function(baseDate, weekth, weekday){
// parse base date
var date = moment(baseDate);
var year = date.year();
var month = date.month();
// Convert date to moment (month 0-11)
var myMonth = moment({year: year, month: month});
// assume we won't have to move forward any number of weeks
var weeksToAdvance = weekth-1;
// Get first weekday of the first week of the month
var firstOccurranceOfDay = myMonth.weekday(weekday);
// Check if first weekday occurrance is in the given month
if( firstOccurranceOfDay.month() != month ){
weeksToAdvance++;
}
// Return nth weekday of month formatted (custom format)
return firstOccurranceOfDay.add(weeksToAdvance, 'weeks');
}
Based on @VincenzoC.
This allows me to send in a moment and receive back a moment.
let getThirdFriday: function(mDate) {
// Based on https://stackoverflow.com/a/34278588
// By default we will need to add two weeks to the first friday
let nWeeks = 2,
month = mDate.month();
// Get first Friday of the first week of the month
mDate = mDate.date(1).day(5);
// Check if first Friday is in the given month
// it may have gone to the previous month
if (mDate.month() != month) {
nWeeks++;
}
// Return 3rd Friday of the month formatted (custom format)
return mDate.add(nWeeks, 'weeks');
}
Then I can call it like:
let threeMonth = getThirdFriday(
moment()
.add(3, 'months')
).format("YYYY-MM-DD");
© 2022 - 2024 — McMap. All rights reserved.