Moment js get specific day of a month by week and day of week
Asked Answered
C

4

5

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.

Chiro answered 12/7, 2017 at 11:12 Comment(3)
Probably I didn't get exactly what you are asking, but see here (and here) to get possible solution to similar question.Kaela
they only work for one specific day. My requirement is for any day of any week.Chiro
In the linked answer day of the week is "hard coded", but I think it's easy to get a more general solution starting from that answer. Anyway I've posted an updated answer with my attempt to get any day of any week.Kaela
K
6

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>
Kaela answered 12/7, 2017 at 14:21 Comment(0)
C
3
//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 a given month.
dayOfWeek is the moment js ISO day of week and
weeknumber is the week number(1,2,3,4) you want

Chiro answered 12/7, 2017 at 11:12 Comment(0)
N
0

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>
Novelty answered 12/7, 2017 at 14:59 Comment(0)
D
0

This code will get the date of the 2nd Tuesday of this month. Note: moment.js is obsolete now, use Luxon instead.

var DateTime = luxon.DateTime;

const second_tuesday = DateTime.local().startOf("month").plus({ weeks: 1, days: 3 });

console.log(second_tuesday.toLocaleString(DateTime.DATE_SHORT));
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
Descendant answered 27/7, 2018 at 16:20 Comment(1)
Sadly if your date is 01-04-2023 and you want 1st Week and week_day 0 (Sunday) you get back 02-04-2023 :(Arhat

© 2022 - 2024 — McMap. All rights reserved.