Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the last friday of the month with momentjs

How could I calculate the last friday of this month using the momentjs api?

like image 604
eddiec Avatar asked Jan 27 '26 17:01

eddiec


2 Answers

Correct answer to this question:

var lastFriday = function () {
  var lastDay = moment().endOf('month');
  if (lastDay.day() >= 5)
   var sub = lastDay.day() - 5;
  else
   var sub = lastDay.day() + 2;
  return lastDay.subtract(sub, 'days');
}

The previous answer returns the next to last friday if the last day of the month is friday.

like image 179
barczag Avatar answered Jan 29 '26 06:01

barczag


Given a moment in the month you want the last Friday for:

var lastFridayForMonth = function (monthMoment) {
  var lastDay = monthMoment.endOf('month').startOf('day');
  switch (lastDay.day()) {
    case 6:
      return lastDay.subtract(1, 'days');
    default:
      return lastDay.subtract(lastDay.day() + 2, 'days');
  }
},

E.g.

// returns moment('2014-03-28 00:00:00');
lastFridayForMonth(moment('2014-03-14));
like image 21
afternoon Avatar answered Jan 29 '26 07:01

afternoon