given a date and a cron expression can you validate that the date is part of the cron expression

Viewed 173

I have a cron expression and i need to check if a certain Date is part of it.(meaning the cron would trigger at that Date) (using nodejs)

1 Answers

You can use cron-parser package and do something like this:

const isDateMatchesCronExpression = (expression, date, scope = 'second') => {
  scope = ['second', 'minute', 'hour', 'day', 'month', 'weekday'].indexOf(scope.toLowerCase());
  try {
    const data = cronParser.parseExpression(expression).fields;

    if (scope <= 0 && !data.second.includes(date.getSeconds())) return false;
    if (scope <= 1 && !data.minute.includes(date.getMinutes())) return false;
    if (scope <= 2 && !data.hour.includes(date.getHours())) return false;
    if (scope <= 3 && !data.dayOfMonth.includes(date.getDate())) return false;
    if (scope <= 4 && !data.month.includes(date.getMonth() + 1)) return false;
    if (scope <= 5 && !data.dayOfWeek.includes(date.getDay())) return false;

    return true;
  } catch (e) {
    throw new Error(`isDateMatchesCronExpression error: ${e}`);
  }
};
Related