Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment js get specific day of a month by week and day of week

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.

like image 458
Venkata K. C. Tata Avatar asked Mar 09 '23 15:03

Venkata K. C. Tata


1 Answers

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>
like image 123
VincenzoC Avatar answered Apr 26 '23 23:04

VincenzoC