Skip to content

Instantly share code, notes, and snippets.

@emanuelet
Created May 10, 2021 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emanuelet/51c0423f3b7290b163c113f38720a1d8 to your computer and use it in GitHub Desktop.
Save emanuelet/51c0423f3b7290b163c113f38720a1d8 to your computer and use it in GitHub Desktop.
Convert Cron expression to RRule string
const parser = require('cron-parser')
const { RRule } = require('rrule')
const logger = require('tracer').colorConsole()
const maps = {
dayofmonth: 'bymonthday',
dayofweek: 'byweekday',
}
module.exports = {
convert: function (expr, currentDate, endDate) {
try {
let interval = parser.parseExpression(expr, {
currentDate: new Date(currentDate),
endDate: new Date(endDate),
})
// Does not support yet RRule.HOURLY and RRule.MINUTELY
let freq =
interval.fields.month.length === 12 &&
interval.fields.dayOfMonth.length === 31 &&
interval.fields.dayOfWeek.length === 8
? 'DAILY'
: interval.fields.month.length === 12 &&
interval.fields.dayOfWeek.length === 8
? 'MONTHLY'
: interval.fields.dayOfMonth.length === 1 &&
interval.fields.month.length === 1
? 'YEARLY'
: 'WEEKLY'
let rule = new RRule({
freq: RRule[freq],
...Object.keys(interval.fields).reduce(function (result, key) {
result[
key.includes('day') ? maps[key.toLowerCase()] : `by${key}`
] = key.includes('day')
? interval.fields[key] - 1
: interval.fields[key]
return result
}, {}),
dtstart: currentDate,
until: endDate,
})
return rule.toString()
} catch (err) {
logger.error(err.message)
}
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment