简体   繁体   中英

MomentJS - how to select all days of the week by name?

How to sellect all same weekdays by using momentJS? Ex: All Mondays of current month. If the day is 15th day of the month, there are two Mondays in that month, from 0 to 15th day of the month. Maybe it is some kind of looping, because momenthJS should return two dates-one for first Monday and second for second Monday in the given range and so on.

Or is there any other way to do this by using any other JavaScript library?

As you said a loop can solve this problem

  • move 4 weeks before from the date you have eg if we were on the last monday of the month we move to the first monday of the month or a previous date (if we move to the previous month we can still get the correct dates by doing more iterations)
  • get the month of the date you have (all the dates you get should have the same month)
  • move forward from the initial date computed above a week each time and check if the new date has the same month as the input date

 function weekdaysFromMonth (date) { // all the weekdays previous/next to date should be // 7 days apart and also have the same month var month = date.get('month') // make sure that the start date is 4 weeks before now // we might go to the previous month but anyway we'll // get the correct dates by doing more iterations var start = moment(date).subtract(4 * 7, 'days') var dates = [] for (var i = 0; i < 10; i += 1) { start.add(7, 'days') if (start.get('month') === month) { dates.push(moment(start)) } } return dates } document.write( JSON.stringify( weekdaysFromMonth(moment()), null, ' ' ) ) 
 <script src="http://momentjs.com/downloads/moment.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM