简体   繁体   中英

Nth day of the Month

I'm using momentjs plugin moment-recur to create and manipulate recurring dates in a client application. I am able to create all types of recurring dates (daily, monthly, annually) but cannot figure out how to create a recurring date for the Nth day of the Month. ie the 1st Friday of September.

I have been able to produce a recurring date for the Nth week of the month which is close but for months that start on a Saturday, the library skips over to the next year when I need it to return the Friday of the following week. You can see that the 1st Friday in September, 2012 is the 7th, but since the month started the week before on Saturday, it determines there is no Friday using the following code:

var start, end;
start = '09/05/1986';
end = '09/05/2014';

var date = moment(start);

//date.day() == 5, which results in Friday
var occurence = date.recur(end).every(date.day()).dayOfWeek();

//date.monthWeek() == 1, 1st week of the month THIS is where the problem lies
occurence = occurence.every(date.monthWeek()).weekOfMonth();

//September
occurence = occurence.every(date.format("MMMM")).monthOfYear();

console.log(occurence.next(50, 'L'));

Prints

... "09/03/2010", "09/02/2011", "09/06/2013", "09/05/2014" ... skipping 2012

JSFiddle Example

Does anyone know how to produce recurring dates for the Nth day of a month with moment-recur or with any other JS library?

Seems to be easy with https://github.com/jakubroztocil/rrule . See https://jakubroztocil.github.io/rrule/ to test:

  • First Friday in September is

     rule = new RRule({ freq: RRule.YEARLY, byweekday: RRule.FR, bymonth: [9], bysetpos: [1] }) 

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