Parse multiple formats with date-fns

Viewed 882

I have this code example:

function compareDate(value: string) {
  return isBefore(
    parse(value, 'dd-MM-yyyy', new Date()),
    sub(new Date(), { days: 1 })
  );
}

const test = compareDate('31-12-2020');

in parse() I need to use dd-MM-yyyy, but also dd/MM/yyyy and dd MM yyyy. How can I achieve this? The value will have date typed by user, typeof String and will look like above examples.

2 Answers

You can use isMatch to determine which string you have:

function compareDate(value: string) {
  let start;
  if (isMatch(value, 'dd-MM-yyyy')) {
    start = parse(value, 'dd-MM-yyyy', new Date());
  } else if (isMatch(value, 'dd/MM/yyyy')) {
    // etc...
  }
  return isBefore(
    start,
    sub(new Date(), { days: 1 })
  );
}

Replace all possible separators with the correct one:

function compareDate(value: string) {
  return isBefore(
    parse(value.replace(/[\/ ]/g, '-'), 'dd-MM-yyyy', new Date()),
    sub(new Date(), { days: 1 })
  )
}

const test = compareDate('31-12-2020')
Related