Question

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

Était-ce utile?

La solution 2

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));

Autres conseils

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.

Sorry guys but I tested previous answers and all of them are wrong.

Check all of them for

moment([2017,2])

And you will find that the result is incorrect.

I wrote this solution which is working so far:

let date = moment([2017,2]).endOf('month'); 

while (date.day() !== 5) { 
  date.subtract(1,'days')
}

return date;

Shorter answer :

var lastFridayForMonth = function (monthMoment) {
    let lastDay = monthMoment.endOf('month').endOf('day');
    return lastDay.subtract((lastDay.day() + 2) % 7, 'days');
}

I tried testing multiple months and for few months above answer by @afternoon did not work. Below is the test code.(one such test is for Aug 2018)

var moment  = require('moment')
var affirm  = require("affirm.js")
var cc = moment(Date.now())
for (var i = 0; i < 100000; i++) {
    lastFridayForMonth(cc)
    var nextWeek = moment(cc).add(7, 'days')
    console.log(cc.format("ddd DD MMM YYYY"), nextWeek.format('MMM'))
    affirm((cc.month() - nextWeek.month()) === -1 || (cc.month() - nextWeek.month()) === 11, "1 month gap is not found")
    affirm(cc.day() === 5, "its not friday")
    cc.add(1, "months")
}

I have put another solution

function lastFridayForMonth(monthMoment) {
    var month = monthMoment.month()
    monthMoment.endOf("month").startOf("isoweek").add(4, "days")
    if (monthMoment.month() !== month) monthMoment.subtract(7, "days")
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top