Rrule package is the Javascript package to generate array of dates for recurring event, special when you are implementing UI like google calendar, recursive event creator when event might repeat for a year on daily basic.

rrule.js supports recurrence rules as defined in the iCalendar RFC, with a few important differences. It is a partial port of the rrule module from the excellent python-dateutil library. On top of that, it supports parsing and serialization of recurrence rules from and to natural language.

In this article, we will look at the basic implementation and important aspect of rrules.

Installation:

Add rrule to your project using npm or yarn.

npm install rrule

  

Basic Usage

RRules export three classes: RRule, RRuleSet and rrulestr. Let see the example to understand the basic usage.

import { RRule, RRuleSet, rrulestr } from 'rrule';

const rule = new RRule({
  freq: RRule.WEEKLY, 
  byweekday: [RRule.MO, RRule.FR],
  dtstart: new Date(Date.UTC(2012, 1, 1, 10, 30)),
  until: new Date(Date.UTC(2012, 12, 31))
});


const dates = rule.all()

[ '2012-02-03T10:30:00.000Z',
  '2012-03-05T10:30:00.000Z',
  '2012-03-09T10:30:00.000Z',
  '2012-04-09T10:30:00.000Z',
  '2012-04-13T10:30:00.000Z',
  '2012-05-14T10:30:00.000Z',
  '2012-05-18T10:30:00.000Z',
 
 /* … */]

Above example will generate all the dates for the recurring event. You can also use rrulestr to parse the string to RRule object.

Dealing with timezone

As we know, dealing with timezone is little tricky in javascript. By default, RRule deals in "floating" times or UTC timezones.. If you want results in a specific timezone, RRule also provides timezone support. Below is the example:

new RRule({
  dtstart: new Date(Date.UTC(2018, 1, 1, 10, 30)),
  count: 1,
  tzid: 'Asia/Tokyo'
}).all()

  

Assuming the system timezone is set to America/Los_Angeles, you get:
[ '2018-01-31T17:30:00.000Z' ]
which is the time in Los Angeles when it’s 2018-02-01T10:30:00 in Tokyo

Store and parse recurring date in string

RRules provide a rrulestr api to extract a date from string. Its mean you can store it in string. Example below will explain the concept better.

// Parse a RRule string, return a RRule object
rrulestr('DTSTART:20120201T023000Z\nRRULE:FREQ=MONTHLY;COUNT=5')

Fairly clear, we have store a recurring date in string where DTSTART indicate start date, FREQ=MONTHLY mean it is repeated monthly and count state that it will re-occurs for next five month.

Conclusion

RRule is a great package to generate recurring date in javascript. It is very easy to use and provide a lot of options to generate recurring date. I hope this article will help you to understand the basic usage of rrule.


For more read official documentation

Read more in official docs here