GithubHelp home page GithubHelp logo

jkbrzt / rrule Goto Github PK

View Code? Open in Web Editor NEW
3.2K 61.0 500.0 4.49 MB

JavaScript library for working with recurrence rules for calendar dates as defined in the iCalendar RFC and more.

Home Page: https://jkbrzt.github.io/rrule

License: Other

JavaScript 1.81% TypeScript 98.17% Shell 0.03%
recurrence-rules javascript rrule library calendar icalendar-rfc rfc python-dateutil jakubroztocil typescript

rrule's Introduction

rrule.js

Library for working with recurrence rules for calendar dates.

NPM version Build Status js-standard-style Downloads Gitter codecov.io

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.


Quick Start

  • Demo app
  • For contributors and maintainers: the code for the demo app is only on gh-pages branch

Client Side

$ yarn add rrule

Server Side

Includes optional TypeScript types

$ yarn add rrule
# or
$ npm install rrule

Usage

RRule:

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

// Create a rule:
const rule = new RRule({
  freq: RRule.WEEKLY,
  interval: 5,
  byweekday: [RRule.MO, RRule.FR],
  dtstart: datetime(2012, 2, 1, 10, 30),
  until: datetime(2012, 12, 31)
})

// Get all occurrence dates (Date instances):
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',

 /* … */]

// Get a slice:
rule.between(datetime(2012, 8, 1), datetime(2012, 9, 1))
['2012-08-27T10:30:00.000Z',
 '2012-08-31T10:30:00.000Z']

// Get an iCalendar RRULE string representation:
// The output can be used with RRule.fromString().
rule.toString()
"DTSTART:20120201T093000Z\nRRULE:FREQ=WEEKLY;INTERVAL=5;UNTIL=20130130T230000Z;BYDAY=MO,FR"

// Get a human-friendly text representation:
// The output can be used with RRule.fromText().
rule.toText()
"every 5 weeks on Monday, Friday until January 31, 2013"

RRuleSet:

const rruleSet = new RRuleSet()

// Add a rrule to rruleSet
rruleSet.rrule(
  new RRule({
    freq: RRule.MONTHLY,
    count: 5,
    dtstart: datetime(2012, 2, 1, 10, 30),
  })
)

// Add a date to rruleSet
rruleSet.rdate(datetime(2012, 7, 1, 10, 30))

// Add another date to rruleSet
rruleSet.rdate(datetime(2012, 7, 2, 10, 30))

// Add a exclusion rrule to rruleSet
rruleSet.exrule(
  new RRule({
    freq: RRule.MONTHLY,
    count: 2,
    dtstart: datetime(2012, 3, 1, 10, 30),
  })
)

// Add a exclusion date to rruleSet
rruleSet.exdate(datetime(2012, 5, 1, 10, 30))

// Get all occurrence dates (Date instances):
rruleSet.all()[
  ('2012-02-01T10:30:00.000Z',
  '2012-05-01T10:30:00.000Z',
  '2012-07-01T10:30:00.000Z',
  '2012-07-02T10:30:00.000Z')
]

// Get a slice:
rruleSet.between(datetime(2012, 2, 1), datetime(2012, 6, 2))[
  ('2012-05-01T10:30:00.000Z', '2012-07-01T10:30:00.000Z')
]

// To string
rruleSet.valueOf()[
  ('DTSTART:20120201T023000Z',
  'RRULE:FREQ=MONTHLY;COUNT=5',
  'RDATE:20120701T023000Z,20120702T023000Z',
  'EXRULE:FREQ=MONTHLY;COUNT=2',
  'EXDATE:20120601T023000Z')
]

// To string
rruleSet.toString()
;('["DTSTART:20120201T023000Z","RRULE:FREQ=MONTHLY;COUNT=5","RDATE:20120701T023000Z,20120702T023000Z","EXRULE:FREQ=MONTHLY;COUNT=2","EXDATE:20120601T023000Z"]')

rrulestr:

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

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

// Parse a RRuleSet string, return a RRuleSet object
rrulestr(
  'DTSTART:20120201T023000Z\nRRULE:FREQ=MONTHLY;COUNT=5\nRDATE:20120701T023000Z,20120702T023000Z\nEXRULE:FREQ=MONTHLY;COUNT=2\nEXDATE:20120601T023000Z'
)

Important: Use UTC dates

Dates in JavaScript are tricky. RRule tries to support as much flexibility as possible without adding any large required 3rd party dependencies, but that means we also have some special rules.

By default, RRule deals in "floating" times or UTC timezones. If you want results in a specific timezone, RRule also provides timezone support. Either way, JavaScript's built-in "timezone" offset tends to just get in the way, so this library simply doesn't use it at all. All times are returned with zero offset, as though it didn't exist in JavaScript.

THE BOTTOM LINE: Returned "UTC" dates are always meant to be interpreted as dates in your local timezone. This may mean you have to do additional conversion to get the "correct" local time with offset applied.

For this reason, it is highly recommended to use timestamps in UTC eg. new Date(Date.UTC(...)). Returned dates will likewise be in UTC (except on Chrome, which always returns dates with a timezone offset). It's recommended to use the provided datetime() helper, which creates dates in the correct format using a 1-based month.

For example:

// local machine zone is America/Los_Angeles
const rule = RRule.fromString(
  "DTSTART;TZID=America/Denver:20181101T190000;\n"
  + "RRULE:FREQ=WEEKLY;BYDAY=MO,WE,TH;INTERVAL=1;COUNT=3"
)
rule.all()

[ 2018-11-01T18:00:00.000Z,
  2018-11-05T18:00:00.000Z,
  2018-11-07T18:00:00.000Z ]
// Even though the given offset is `Z` (UTC), these are local times, not UTC times.
// Each of these this is the correct local Pacific time of each recurrence in
// America/Los_Angeles when it is 19:00 in America/Denver, including the DST shift.

// You can get the local components by using the getUTC* methods eg:
date.getUTCDate() // --> 1
date.getUTCHours() // --> 18

If you want to get the same times in true UTC, you may do so (e.g., using Luxon):

rule.all().map(date =>
DateTime.fromJSDate(date)
  .toUTC()
  .setZone('local', { keepLocalTime: true })
  .toJSDate()
)

[ 2018-11-02T01:00:00.000Z,
  2018-11-06T02:00:00.000Z,
  2018-11-08T02:00:00.000Z ]
// These times are in true UTC; you can see the hours shift

For more examples see python-dateutil documentation.


Timezone Support

Rrule also supports use of the TZID parameter in the RFC using the Intl API. Support matrix for the Intl API applies. If you need to support additional environments, please consider using a polyfill.

Example with TZID:

new RRule({
  dtstart: datetime(2018, 2, 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.

Whether or not you use the TZID param, make sure to only use JS Date objects that are represented in UTC to avoid unexpected timezone offsets being applied, for example:

// WRONG: Will produce dates with TZ offsets added
new RRule({
  freq: RRule.MONTHLY,
  dtstart: new Date(2018, 1, 1, 10, 30),
  until: new Date(2018, 2, 31),
}).all()[('2018-02-01T18:30:00.000Z', '2018-03-01T18:30:00.000Z')]

// RIGHT: Will produce dates with recurrences at the correct time
new RRule({
  freq: RRule.MONTHLY,
  dtstart: datetime(2018, 2, 1, 10, 30),
  until: datetime(2018, 3, 31),
}).all()[('2018-02-01T10:30:00.000Z', '2018-03-01T10:30:00.000Z')]

API

RRule Constructor

new RRule(options[, noCache=false])

The options argument mostly corresponds to the properties defined for RRULE in the iCalendar RFC. Only freq is required.

Option Description
freq

(required) One of the following constants:

  • RRule.YEARLY
  • RRule.MONTHLY
  • RRule.WEEKLY
  • RRule.DAILY
  • RRule.HOURLY
  • RRule.MINUTELY
  • RRule.SECONDLY
dtstart The recurrence start. Besides being the base for the recurrence, missing parameters in the final recurrence instances will also be extracted from this date. If not given, new Date will be used instead. **IMPORTANT:** See the discussion under timezone support
interval The interval between each freq iteration. For example, when using RRule.YEARLY, an interval of 2 means once every two years, but with RRule.HOURLY, it means once every two hours. The default interval is 1.
wkst The week start day. Must be one of the RRule.MO, RRule.TU, RRule.WE constants, or an integer, specifying the first day of the week. This will affect recurrences based on weekly periods. The default week start is RRule.MO.
count How many occurrences will be generated.
until If given, this must be a Date instance, that will specify the limit of the recurrence. If a recurrence instance happens to be the same as the Date instance given in the until argument, this will be the last occurrence.
tzid If given, this must be a IANA string recognized by the Intl API. See discussion under Timezone support.
bysetpos If given, it must be either an integer, or an array of integers, positive or negative. Each given integer will specify an occurrence number, corresponding to the nth occurrence of the rule inside the frequency period. For example, a bysetpos of -1 if combined with a RRule.MONTHLY frequency, and a byweekday of (RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR), will result in the last work day of every month.
bymonth If given, it must be either an integer, or an array of integers, meaning the months to apply the recurrence to.
bymonthday If given, it must be either an integer, or an array of integers, meaning the month days to apply the recurrence to.
byyearday If given, it must be either an integer, or an array of integers, meaning the year days to apply the recurrence to.
byweekno If given, it must be either an integer, or an array of integers, meaning the week numbers to apply the recurrence to. Week numbers have the meaning described in ISO8601, that is, the first week of the year is that containing at least four days of the new year.
byweekday If given, it must be either an integer (0 == RRule.MO), an array of integers, one of the weekday constants (RRule.MO, RRule.TU, etc), or an array of these constants. When given, these variables will define the weekdays where the recurrence will be applied. It's also possible to use an argument n for the weekday instances, which will mean the nth occurrence of this weekday in the period. For example, with RRule.MONTHLY, or with RRule.YEARLY and BYMONTH, using RRule.FR.nth(+1) or RRule.FR.nth(-1) in byweekday will specify the first or last friday of the month where the recurrence happens. Notice that the RFC documentation, this is specified as BYDAY, but was renamed to avoid the ambiguity of that argument.
byhour If given, it must be either an integer, or an array of integers, meaning the hours to apply the recurrence to.
byminute If given, it must be either an integer, or an array of integers, meaning the minutes to apply the recurrence to.
bysecond If given, it must be either an integer, or an array of integers, meaning the seconds to apply the recurrence to.
byeaster This is an extension to the RFC specification which the Python implementation provides. Not implemented in the JavaScript version.

noCache: Set to true to disable caching of results. If you will use the same rrule instance multiple times, enabling caching will improve the performance considerably. Enabled by default.

See also python-dateutil documentation.


Instance properties

rule.options
Processed options applied to the rule. Includes default options (such us wkstart). Currently, rule.options.byweekday isn't equal to rule.origOptions.byweekday (which is an inconsistency).
rule.origOptions
The original options argument passed to the constructor.

Occurrence Retrieval Methods

RRule.prototype.all([iterator])

Returns all dates matching the rule. It is a replacement for the iterator protocol this class implements in the Python version.

As rules without until or count represent infinite date series, you can optionally pass iterator, which is a function that is called for each date matched by the rule. It gets two parameters date (the Date instance being added), and i (zero-indexed position of date in the result). Dates are being added to the result as long as the iterator returns true. If a false-y value is returned, date isn't added to the result and the iteration is interrupted (possibly prematurely).

rule.all()[
  ('2012-02-01T10:30:00.000Z',
  '2012-05-01T10:30:00.000Z',
  '2012-07-01T10:30:00.000Z',
  '2012-07-02T10:30:00.000Z')
]

rule.all(function (date, i) {
  return i < 2
})[('2012-02-01T10:30:00.000Z', '2012-05-01T10:30:00.000Z')]
RRule.prototype.between(after, before, inc=false [, iterator])

Returns all the occurrences of the rrule between after and before. The inc keyword defines what happens if after and/or before are themselves occurrences. With inc == true, they will be included in the list, if they are found in the recurrence set.

Optional iterator has the same function as it has with RRule.prototype.all().

rule.between(datetime(2012, 8, 1), datetime(2012, 9, 1))[
  ('2012-08-27T10:30:00.000Z', '2012-08-31T10:30:00.000Z')
]
RRule.prototype.before(dt, inc=false)

Returns the last recurrence before the given Date instance. The inc argument defines what happens if dt is an occurrence. With inc == true, if dt itself is an occurrence, it will be returned.

RRule.prototype.after(dt, inc=false)

Returns the first recurrence after the given Date instance. The inc argument defines what happens if dt is an occurrence. With inc == true, if dt itself is an occurrence, it will be returned.

See also python-dateutil documentation.


iCalendar RFC String Methods

RRule.prototype.toString()

Returns a string representation of the rule as per the iCalendar RFC. Only properties explicitly specified in options are included:

rule.toString()
;('DTSTART:20120201T093000Z\nRRULE:FREQ=WEEKLY;INTERVAL=5;UNTIL=20130130T230000Z;BYDAY=MO,FR')

rule.toString() == RRule.optionsToString(rule.origOptions)
true
RRule.optionsToString(options)

Converts options to iCalendar RFC RRULE string:

// Get full a string representation of all options,
// including the default and inferred ones.
RRule.optionsToString(rule.options)
;('DTSTART:20120201T093000Z\nRRULE:FREQ=WEEKLY;INTERVAL=5;WKST=0;UNTIL=20130130T230000Z;BYDAY=MO,FR;BYHOUR=10;BYMINUTE=30;BYSECOND=0')

// Cherry-pick only some options from an rrule:
RRule.optionsToString({
  freq: rule.options.freq,
  dtstart: rule.options.dtstart,
})
;('DTSTART:20120201T093000Z\nRRULE:FREQ=WEEKLY;')
RRule.fromString(rfcString)

Constructs an RRule instance from a complete rfcString:

var rule = RRule.fromString('DTSTART:20120201T093000Z\nRRULE:FREQ=WEEKLY;')

// This is equivalent
var rule = new RRule(
  RRule.parseString('DTSTART:20120201T093000Z\nRRULE:FREQ=WEEKLY')
)
RRule.parseString(rfcString)

Only parse RFC string and return options.

var options = RRule.parseString('FREQ=DAILY;INTERVAL=6')
options.dtstart = datetime(2000, 2, 1)
var rule = new RRule(options)

Natural Language Text Methods

These methods provide an incomplete support for text→RRule and RRule→text conversion. You should test them with your input to see whether the result is acceptable.

RRule.prototype.toText([gettext, [language]])

Returns a textual representation of rule. The gettext callback, if provided, will be called for each text token and its return value used instead. The optional language argument is a language definition to be used (defaults to rrule/nlp.js:ENGLISH).

var rule = new RRule({
  freq: RRule.WEEKLY,
  count: 23,
})
rule.toText()
;('every week for 23 times')
RRule.prototype.isFullyConvertibleToText()

Provides a hint on whether all the options the rule has are convertible to text.

RRule.fromText(text[, language])

Constructs an RRule instance from text.

rule = RRule.fromText('every day for 3 times')
RRule.parseText(text[, language])

Parse text into options:

options = RRule.parseText('every day for 3 times')
// {freq: 3, count: "3"}
options.dtstart = datetime(2000, 2, 1)
var rule = new RRule(options)

RRuleSet Constructor

new RRuleSet([(noCache = false)])

The RRuleSet instance allows more complex recurrence setups, mixing multiple rules, dates, exclusion rules, and exclusion dates.

Default noCache argument is false, caching of results will be enabled, improving performance of multiple queries considerably.

RRuleSet.prototype.rrule(rrule)

Include the given rrule instance in the recurrence set generation.

RRuleSet.prototype.rdate(dt)

Include the given datetime instance dt in the recurrence set generation.

RRuleSet.prototype.exrule(rrule)

Include the given rrule instance in the recurrence set exclusion list. Dates which are part of the given recurrence rules will not be generated, even if some inclusive rrule or rdate matches them. NOTE: EXRULE has been (deprecated in RFC 5545)[https://icalendar.org/iCalendar-RFC-5545/a-3-deprecated-features.html] and does not support a DTSTART property.

RRuleSet.prototype.exdate(dt)

Include the given datetime instance dt in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them.

RRuleSet.prototype.tzid(tz?)

Sets or overrides the timezone identifier. Useful if there are no rrules in this RRuleSet and thus no DTSTART.

RRuleSet.prototype.all([iterator])

Same as RRule.prototype.all.

RRuleSet.prototype.between(after, before, inc=false [, iterator])

Same as RRule.prototype.between.

RRuleSet.prototype.before(dt, inc=false)

Same as RRule.prototype.before.

RRuleSet.prototype.after(dt, inc=false)

Same as RRule.prototype.after.

RRuleSet.prototype.rrules()

Get list of included rrules in this recurrence set.

RRuleSet.prototype.exrules()

Get list of excluded rrules in this recurrence set.

RRuleSet.prototype.rdates()

Get list of included datetimes in this recurrence set.

RRuleSet.prototype.exdates()

Get list of excluded datetimes in this recurrence set.


rrulestr Function

rrulestr(rruleStr[, options])

The rrulestr function is a parser for RFC-like syntaxes. The string passed as parameter may be a multiple line string, a single line string, or just the RRULE property value.

Additionally, it accepts the following keyword arguments:

cache
If true, the rruleset or rrule created instance will cache its results. Default is not to cache.
dtstart
If given, it must be a datetime instance that will be used when no DTSTART property is found in the parsed string. If it is not given, and the property is not found, datetime.now() will be used instead.
unfold
If set to true, lines will be unfolded following the RFC specification. It defaults to false, meaning that spaces before every line will be stripped.
forceset
If set to true, an rruleset instance will be returned, even if only a single rule is found. The default is to return an rrule if possible, and an rruleset if necessary.
compatible
If set to true, the parser will operate in RFC-compatible mode. Right now it means that unfold will be turned on, and if a DTSTART is found, it will be considered the first recurrence instance, as documented in the RFC.
tzid
If given, it must be a string that will be used when no TZID property is found in the parsed string. If it is not given, and the property is not found, 'UTC' will be used by default.

Differences From iCalendar RFC

  • RRule has no byday keyword. The equivalent keyword has been replaced by the byweekday keyword, to remove the ambiguity present in the original keyword.
  • Unlike documented in the RFC, the starting datetime, dtstart, is not the first recurrence instance, unless it does fit in the specified rules. This is in part due to this project being a port of python-dateutil, which has the same non-compliant functionality. Note that you can get the original behavior by using a RRuleSet and adding the dtstart as an rdate.
var rruleSet = new RRuleSet()
var start = datetime(2012, 2, 1, 10, 30)

// Add a rrule to rruleSet
rruleSet.rrule(
  new RRule({
    freq: RRule.MONTHLY,
    count: 5,
    dtstart: start,
  })
)

// Add a date to rruleSet
rruleSet.rdate(start)
  • Unlike documented in the RFC, every keyword is valid on every frequency. (The RFC documents that byweekno is only valid on yearly frequencies, for example.)

Development

rrule.js is implemented in Typescript. It uses JavaScript Standard Style coding style.

To run the code, checkout this repository and run:

$ yarn

To run the tests, run:

$ yarn test

To build files for distribution, run:

$ yarn build

Authors

Python dateutil is written by Gustavo Niemeyer.

See LICENCE for more details.

Related projects

  • https://rrules.com — RESTful API to get back occurrences of RRULEs that conform to RFC 5545.

rrule's People

Contributors

aferre avatar arolson101 avatar bubbatls avatar circlingthesun avatar david-golightly-leapyear avatar davidgoli avatar db82407 avatar epicfaace avatar fleeting avatar hgrsd avatar isayme avatar island205 avatar jeffijoe avatar jeffreykwan avatar jessevogt avatar jkbrzt avatar jkronborg avatar john-d-pelingo avatar johnnyfreeman avatar jonhageman avatar kourge avatar lespacedunmatin avatar linquize avatar mchapman avatar nickarora avatar paulbalomiri avatar polo2ro avatar wombleton avatar yitomok avatar zensh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rrule's Issues

nlp doesn't work :(

Hi,

Have you an example in an other langage because nlp use only english...

Thanks for your help.

RFC 5545

Hello,

any plan to support the new RFC? http://tools.ietf.org/html/rfc5545
I need to get result RRULE string to be parsed with a library that uses this more recent version of the specification that differs slightly from the one you are using.

Thanks in advance and keep doing the good work ;)

Documentation for i18n of toText

Please add better documentation about i18n of the toText() method.

  1. What's the meaning of the today parameter?
  2. Which values are passed to gettext?
  3. How do I actually translate stuff? I'm able to change dayNames and monthNames, but that's only part of it.

Thank you for creating this lib!

Can not set negative values to bysetpos in demo

Additional brackets are needed in Line 175 in demo.js

current:

           } else if (/^by/.test(key)) {
              if (!value instanceof Array) { // <---
                value = value.split(/[,\s]+/);
              }

correct version:

           } else if (/^by/.test(key)) {
              if (!(value instanceof Array)) { // <---
                value = value.split(/[,\s]+/);
              }

Consider swapping to lodash

I was pointed here by @bdufresne who's using rrule with classic ASP which apparently works with lodash but not underscore.
With lodash snippets like npl line #84 can be simplified to:

   allWeeks:_.reject(byweekday,'n'),
   someWeeks:_.filter(byweekday,'n')

I also noticed you're using return statements with _.each so ya may dig that with lodash _.each supports exiting early by returning false, unlike Underscore.

Lo-Dash also supports deep _.clone and _.merge which you may find useful and has a considerably faster _.include implementation.

If you'd dig a PR just let me know.

Usage of before and after?

var rfcString = 'FREQ=WEEKLY;INTERVAL=2;COUNT=4;BYDAY=TU,SU;WKST=SU'
  , rule
  , d = new Date()
  , previous
  , current
  , current2
  , next
  ;

rule = RRule.fromString(rfcString);

previous = rule.before(d);
current = rule.after(d, true);
current2 = rule.after(d);

if (current.toString() === current2.toString()) {
  next = rule.after(current);
} else {
  next = current2;
}

console.log('Previous:', previous);
console.log('Current:', current);
console.log('Next:', next);

I get the following output:

Previous: null
Current: Sun Jan 26 2014 15:53:20 GMT-0700 (MST)
Next: Tue Jan 28 2014 15:53:20 GMT-0700 (MST)

I would expect this output instead:

Previous: Tue Jan 7 2014 15:53:20 GMT-0700 (MST)
Current: Sun Jan 19 2014 15:53:20 GMT-0700 (MST)
Next: Tue Jan 21 2014 15:53:20 GMT-0700 (MST)

Time Zone Support

Is there a way to get a .between for an RRULE that is in a time zone other than the browser's current time zone? could the library make use of timezone-js to implement this functionality?

For example, if I'm in America/New_York but I have a recurrence that should be interpreted in Europe/Paris, the resulting dates should account for the daylight savings changes in the Europe/Paris time zone.

Edit: Digging deeper, would a change to

tzOffset: function(date) {
  return date.getTimezoneOffset() * 60 * 1000
}

fix this issue?

Recurring events like iCal does

hello there

I've an iCal file containing one recurring event, like this

BEGIN:VEVENT
DTSTART;TZID=Europe/Amsterdam:20110416T193000
DTEND;TZID=Europe/Amsterdam:20110416T203000
RRULE:FREQ=MONTHLY;INTERVAL=2;WKST=MO;BYMONTHDAY=16
DTSTAMP:20131206T093222Z
END:VEVENT

It means that I have an event that:

  • starts on 04/16/2011 at 19.30.00
  • ends on 04/16/2011 at 20.30.00
  • each 2 months
  • on 16th of the month

Can RRule manage this kind of event? How should I build the RRULE string in order to RRule.js can manage this kind of event?

Thanks

Lodash Compat

So I'm just wondering you're going to plan on Lodash compatibility.

Right now rrule.js as is will not work 1:1 with Lodash without some manual patching (such as the chain method being gone) or using a compatibility build which has tons of missing features compared to a non compatibility build.

DTSTART set as datetime.now() instead of first occurrence

Great work! Just one quick enhancement idea...

Kanzaki writes... "The "DTSTART" property defines the first instance in the recurrence set".

In your code it looks like you set dtstart as now() and then derive the byhour and byminute arrays from dtstart.

I might be missing something here, but it seems like instead of setting DTSTART to the first occurrence it sets dtstart to now(), not adhering to the standard.

link: http://www.kanzaki.com/docs/ical/rrule.html

How to set tzid / timezone?

It appears that this uses the local time for calculations, but how do I calculate a schedule for another timezone?

Or perhaps I should call something like this?

date.toString().replace(/GMT.*/, 'GMT' + offset + ' (' + abbr + ')')

Use case:

i.e. I want to set a recurring event for 10am EST but the server that is actually running the code is PST, so despite the fact that the result set is converted to UTC, it's converted to the wrong UTC.

milliseconds truncated for returned occurrences

It appears that milliseconds are not carried forward in occurrences.
I know most occurrences don't matter at the level of milliseconds, but it could be useful in some cases, and it definitely allows me to write simpler tests.

The truncation of milliseconds causes my tests to fail:

expected:
"2014-06-08T16:51:13.976Z"
actual:
"2014-06-08T16:51:13.000Z"

Getting More Information about an RRule

Are there some more methods to get some information about an RRule?

I'm in a use case where for example I get an RRule string of:

FREQ=WEEKLY;BYDAY=TU

I'd like to know that this is an RRule.WEEKLY. Also that it occurs on RRule.TU.

Thanks

toText method has duplicate parameters.

The toText() method has duplicate parameters see:

Line: 879

    /**
    * Will convert all rules described in nlp:ToText
    * to text.
    */
    toText: function(today, today, gettext, language) {
        if (!_.has(this, '_text')) {
            this._text = getnlp().toText(this, today, gettext, language);
        }
        return this._text;
    },

It doesn't seem like you are calling this method anywhere..

JSON (read javascript serialization) support

I want to use this on the client and server, but because of things like RRule.WEEKLY and RRule.WE = new Weekday(2) I can't just send it across.

What do you think about having some logic in the constructor to accept a pure JSON object and a proper .toJSON method?

// Create a rule:
var rule = new RRule({
    freq: 'weekly',
    interval: 5,
    byweekday: ['mo', 'fr'],
    dtstart: new Date(2012, 1, 1, 10, 30).toISOString(),
    until: new Date(2012, 12, 31).toISOString()
});

rule.toJSON();

WKST and toString()

According to the RFC 2445 and 5545, shouldn't the WKST values be converted to the format "MO", "TU", "WE", etc. when calling toString()? Currently WKST values will be outputted as number values which some calendar applications deem invalid.

Extra filtering

Hi
thank you this is good project

I want to add one feature

when freq is RRule.HOURLY or RRule.MINUTELY , RRule.SECONDLY

i need to work in specific time in day

ex: time from 3:00 to 6:00

i need add some Options parameter and filter result

Where do I put this code

thank you for help me

incorrect parsing byyearday, byweekno, byhour, byminute

It seems that double digit integers entered into some of the "by" fields get processed as two individual numbers instead of one value.

For instance, byhour of 10 gets interpreted as BYHOUR=1,0
Therefore, instead of something happening once at 10am, it occurs twice (right after midnight and 1am). Attempting to use "s to indicate a whole number doesn't seem to work. (Trying to separate additional values by ,'s generates NaN errors too)

rrule byhour question

IE8 support broken in 2.1

Just noticed IE8 support was broken when the underscore dependency was removed. This is fine, it'd just be nice to have the doc's or changelog updated to make that clear.

I downgraded to 2.0.0 and it seems to work fine right now. We will probably added in a ES5 Shim and upgrade shortly.

rrule in bower repo doesn't work

I was using bower to checkout this project and it didn't work. When I download rrule.js manually from github then it works. There's indeed some differences between the codes. Perhaps bower version is not updated?

Multidate event with "date_start" and "date_end" of each event occurence

Hi, I've recurring events like this:

FREQ=YEARLY;BYWEEKNO=45;BYDAY=SA,SU,MO;WKST=SA;DTSTART=20131101

Every year every weekno 45 from friday to next monday => MyEvent

1   Sat Nov 02  2013    01:00:00    GMT+0100    (CET)
2   Sun Nov 03  2013    01:00:00    GMT+0100    (CET)
3   Mon Nov 04  2013    01:00:00    GMT+0100    (CET)
4   Sat Nov 08  2014    01:00:00    GMT+0100    (CET)
5   Sun Nov 09  2014    01:00:00    GMT+0100    (CET)
6   Mon Nov 10  2014    01:00:00    GMT+0100    (CET)
7   Sat Nov 07  2015    01:00:00    GMT+0100    (CET)
8   Sun Nov 08  2015    01:00:00    GMT+0100    (CET)
9   Mon Nov 09  2015    01:00:00    GMT+0100    (CET)
10  Sat Nov 05  2016    01:00:00    GMT+0100    (CET)
...

Is possible or would you include in the api something like this:

rule.toEvents();
[
  [Sat  Nov 02  2013    01:00:00    GMT+0100    (CET), Mon  Nov 04  2013    01:00:00    GMT+0100    (CET)],
  [Sat  Nov 08  2014    01:00:00    GMT+0100    (CET), Mon  Nov 10  2014    01:00:00    GMT+0100    (CET)],
 /* [date_start,date_end] */]

I a few words the computation above grouped by adiacents events

hmm, what about weekends?

it seems like there is no mention of sunday saturday and option for every weekend?

I guess I could prob do something like after every friday, before its next monday.

Problem parsing rrule

looks like this rrule is not parsed correctly:
"FREQ=WEEKLY;INTERVAL=1;UNTIL=20130509;BYDAY=MO,TU,WE,TH,FR;WKST=SU"

When select every month on Monday

Hi,

maybe ilt's not a bug, but when i pass

rule =
new RRule({
freq: RRule.MONTHLY,
dtstart: new Date(2013, 11, 31, 15, 0, 0),
byweekday: RRule.MO
})

or in human form : every month on Monday

the resulting is every week on monday.
(the demo show this too)

maybe it's me who misused your library.

thank you for your time and answer
best regard

Suggestion: let the "freq" field contain text to match the RFC 2445 spec

I encountered this issue upon marshalling and unmarshalling data that contains an RRule.

Currently, the rrule.js library expects an integer in the "freq" field.
This works fine, but is incompatible with the RFC 2445 spec.
If I have a recurrence rule specified from another system,
I have to convert the string value of "freq" to the enum integer value used by RRule.
And vice versa when I export such data to another system.
This means I must now support two types for this field.

I have a JSON schema that defines the recurrence according to RFC 2445, as a string enum:

        "freq":    {
            "description": "The frequency.",
            "type": "string",
            "enum": [
                "secondly", "minutely", "hourly", "daily", "weekly", "monthly", "yearly"
            ]
        },

As an experiment, I changed my version of rrule.js to take two fields: "freq" and "freq_n".
"freq" expects a string that matches the spec, and freq_n iis the integer enum value used internally (where the original "freq" was used.)

This seems to work well for me, and solves the marshalling problem.

Tagging Latest Release

Do you mind tagging your latest release? 1.1.0. Bower has basically only tag support until they release a new master. Thanks.

Many tests fail...

Scratching my head for several hours now. It looks like a majority of the test cases fail for me, in fact, the only cases that pass are 1-8 and then a few throughout (very few) and 222-224. It almost looks like to me that RRule is setting the starting day at as a day earlier, as the expected results are behind 1:

testYearly:
Expected:
"Tue Sep 02 1997 09:00:00 GMT-0500 (Central Daylight Time)"
Result:
"Tue Sep 01 1998 09:00:00 GMT-0500 (Central Daylight Time)"

testYearlyByMonthDay:

Expected:
"Wed Sep 03 1997 09:00:00 GMT-0500 (Central Daylight Time)"
Result:
"Tue Sep 02 1997 09:00:00 GMT-0500 (Central Daylight Time)"
Diff:
"Wed "Tue Sep 03 02 1997 09:00:00 GMT-0500 (Central Daylight Time)"
Source:
at assertDatesEqual (file:///D:/Sites/rrule/test/utils.js:52:9)
at Object. (file:///D:/Sites/rrule/test/utils.js:85:9)

etc...

Are you getting the same?

Parse and transform cron expressions

When you want to use rrule with another library that schedules jobs to run, they use cron expressions. It'd be nice to convert an rrule to a cron expression.

byDay Interval

Hi first of all good job so far!
I've might found a problem with the byday rule and intervals.

If u test this rule:
FREQ=DAILY;BYDAY=MO;INTERVAL=3;UNTIL=20131101T000000Z;WKST=MO
It markes the first MO in february and than every third like expected.

If u test this rule where I just switched MO with TU:
FREQ=DAILY;BYDAY=TU;INTERVAL=3;UNTIL=20131101T000000Z;WKST=MO
It starts with the third TU of february. Schouldn't it start at the first TU too?

Thx

Disregard...

** Disregard...forgot about zero indexing...8-) **

var RRule = require('rrule').RRule;
var rule =  RRule.fromString('FREQ=DAILY;DTSTART=20131201T170000Z;WKST=MO;UNTIL=20131231T170000Z');
rule.between(new Date(2013,12,01), new Date(2013,12,31)); // []

rule.between() returns [] using Node 0.10.18 repl under OS X.

Day repeats when day light savings time starts

Daylight savings time starts on the 28 of September in NZ. It looks like RRules doesn't like this date, and pushes every recurrence back 1 day.

Is there any way to fix this, or work around it?

Tested in (UTC+12:00) Auckland, Wellington Chrome:

new RRule({
    freq: RRule.DAILY,
    dtstart: new Date(2014, 8, 26, 10, 30),
    count: 4
}).between(new Date(2014, 8, 26), new Date(2014, 9, 1));

[
    "2014-09-25T22:30:00.000Z",
    "2014-09-26T22:30:00.000Z",
    "2014-09-26T22:30:00.000Z",
    "2014-09-28T21:30:00.000Z"
]

Tested (UTC+10:00) Canberra, Melbourne, Sydney IE9:

new RRule({
    freq: RRule.DAILY,
    dtstart: new Date(2014, 9, 3, 10, 30),
    count: 100
}).between(new Date(2014, 9, 3), new Date(2014, 11, 1));

0 : Fri Oct 3 10:30:00 UTC+1000 2014,
1 : Sat Oct 4 10:30:00 UTC+1000 2014,
2 : Sat Oct 4 10:30:00 UTC+1000 2014,
3 : Mon Oct 6 10:30:00 UTC+1100 2014,

image

Daily Occurance Issue

Please have a look at this rule FREQ=DAILY;COUNT=10;INTERVAL=2;BYDAY=MO,TU,WE,TH,FR.

This should return the dates as
30/10, 1/11, 4/11, 6/11, 8/11, 11/11, 13/11, 15/11, 18/11, 20/11

whereas the library is returning as
30/10, 1/11, 5/11, 7/11 and so on.

As 5/11 falls on Tuesday, why the library missed 4/11.

Any thoughts??

first event being created before wkst?

Unfortunately, I'm not an iCal/rrule expert, so this might be my interpretation being wrong, however, if I set the wkst value to be a day that is after today, I would assume that no events could take place today as part of this rule?

For instance, if today is friday, and i have a weekly rule that repeats on mon/tues/wed/thur/fri and I set the wkst to "SA", shouldn't the first event be monday of next week and NOT today (since friday is before saturday)?

I've attached a screenshot to help explain my question.

Thanks for an amazing script!

Does not produce correct times for dates

Given:
DTSTART: 20070311T020000
RRULE: FREQ=YEARLY;BYMONTH=3;BYDAY=2SU

Produces:
Sun Mar 11 2007 18:00:00 GMT-0700 (PDT),
Sun Mar 09 2008 18:00:00 GMT-0700 (PDT),
Sun Mar 08 2009 18:00:00 GMT-0700 (PDT),
Sun Mar 14 2010 18:00:00 GMT-0700 (PDT),
...
Please Note:
Times are incorrect with respect to the DTSTART

Code to reproduce:

var rrule = require('rrule').RRule;
var options = rrule.parseString('FREQ=YEARLY;BYMONTH=3;BYDAY=2SU');

 if (options) {
    options.dtstart = new Date('2007-03-11T02:00:00');
    var RRule = new rrule(options);
    console.log(RRule.all());
    done();
}

rrule.js path broken in bower.json

When using grunt-bower-install, it puts wrong pathname in index.html to rrule.js, ie. {bower_components}/rrule/rrule.js. I think this can be solved by updating the bower.json file.

Mixed weekday rule bug

I'm not sure if it's just me, or it's actually a bug.

I'm trying to create a rule with mixed options for weekdays (byweekday). Refer to the following line of code:

WKST=SU;FREQ=MONTHLY;INTERVAL=1;BYDAY=MO,-1WE

In that example, I'm trying to create a recurring rule that must be every month on Mondays and on the last Wednesday.

First I thought it was a faulty logic in my code, however upon checking in the demo site (http://jakubroztocil.github.io/rrule/), I discovered that it actually doesn't output anything.

If I remove -1 from WE, meaning the rule would become every month on Mondays and Wednesdays, it works. If I put any nth for Monday, say 2MO, making the rule every month on the 2nd Monday and last Wednesday, it also works.

Is it a bug, or am I doing something wrong?
Thanks.

Only allowing dates after today

If I use this rrule: FREQ=WEEKLY;BYDAY=MO,FR;INTERVAL=5

And do rule.between(moment().subtract('year', 5).toDate(), moment().subtract('year', 4).toDate()); then no dates are found. If instead I do dates in the future such as rule.between(moment().add('year', 4).toDate(), moment().add('year', 5).toDate()); then it works fine.

Subsumption of rules

Great library! I was wondering if it's possible to determine whether one rule subsumes another - that is, whether the recurrence of one rule is a superset of the recurrences of another rule. A simple example could be:

Rule 1: Every monday, wednesday and friday of every week at 9:00am.
Rule 2: Every day of every week at 9:00am.

Here Rule 2 subsumes Rule 1.

A naive approach would be to determine what the period of the recurrence is (e.g. Rule 1 is 1 week, Rule 2 is 1 day) and check whether the rule of longer period can have all recurrences reproduced using the rule of shorter period. A better approach is to deterministically compare the rules. I think a rule subsumes another if:

  • freq must be >=
  • interval must be <=
  • dtstart must be equal or earlier
  • byweekday set of days must be equal or a superset

I'm solving a related problem in my app but I might need this later on. If so I might end up implementing it.

dtstart seems to not be considered in some cases

I just updated to version 2.0.1.

In this example, I expect that after will contain the value of dtstart (which is one_hour_in), and that between will have dtstart as its first value.
However, it is missing in both cases.

This code is for node.js:

var rrule = require('rrule');
var RRule = rrule.RRule;
var start = new Date();
var end   = new Date(start.getTime() + 86400000); // One day after
var one_hour_in = new Date(start.getTime() + 3600000); // One hour after start
var rule = new RRule({
     freq: RRule.HOURLY,
     dtstart: one_hour_in,
     count: 1
 });
var after = rule.after(start);
var between = rule.between(start, end);

Example results:

> start
Fri Jun 06 2014 10:01:00 GMT-0700 (PDT)
> one_hour_in
Fri Jun 06 2014 11:01:00 GMT-0700 (PDT)
> end
Sat Jun 07 2014 10:01:00 GMT-0700 (PDT)

> after
Fri Jun 06 2014 12:01:00 GMT-0700 (PDT)
> between
[ Fri Jun 06 2014 12:01:00 GMT-0700 (PDT) ]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.