Search code examples
javascriptreactjsdate-fns

Parse multiple formats with date-fns


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.


Solution

  • 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')