Dev
Dev

Reputation: 1921

Using momentjs with recurring dates

I have a date which flagged as recurring date (occurs every year), this date is 1st April, 2014, and starting form 2014 this event will occur yearly.

I have a job which run weekly, in this job I insert in the DB events that will occur in the coming 180 days only starting from today, other events will be discarded.

now when in my check, 1st April 2016 is past....so it's discarded (while 1st April 2015 should be added as it's in the range).

I am using momentjs but am not able to find the correct logic for it.

below is my code ....

//desiredDate = today + 180 days

if (isYearlyRecur) {
    var year = eventeDate.getFullYear();
    if (year < currentYear) {
        if (moment(eventeDate).unix() < moment(todayDate).unix()) {
            eventeDate = moment(eventeDate).set('year', currentYear + 1);
        }
        else if (moment(eventeDate).unix() > moment(desiredDate).unix()) {
            eventeDate = moment(eventeDate).set('year', currentYear);
        }
    }
}

what is the correct way to do it and cover if the date comes in next year ...etc

Upvotes: 3

Views: 2892

Answers (1)

John
John

Reputation: 10079

You could use rSchedule for this (a javascript recurrence library which I maintain).

Example:

I have a date which flagged as recurring date (occurs every year), this date is 1st April, 2014, and starting form 2014 this event will occur yearly.

import { Schedule } from '@rschedule/rschedule';
import { MomentDateAdapter } from '@rschedule/moment-date-adapter';
import * as moment from 'moment';

const schedule = new Schedule({
  rrules: [{
    frequency: 'YEARLY',
    start: moment([2014, 3, 1]),
  }],
  dateAdapter: MomentDateAdapter,
});

I have a job which run weekly, in this job I insert in the DB events that will occur in the coming 180 days only starting from today, other events will be discarded.

const next180Days = moment().add(180, 'days').endOf('day');

if (schedule.occursBetween(moment(), next180Days)) {
  // do stuff...
}

Upvotes: 3

Related Questions