使用 date-fns 解析多种格式

Parse multiple formats with date-fns

我有这个代码示例:

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

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

在parse()中我需要使用dd-MM-yyyy,还有dd/MM/yyyydd MM yyyy。我怎样才能做到这一点? 该值将具有用户键入的日期,typeof String,并且看起来像上面的示例。

用正确的分隔符替换所有可能的分隔符:

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

您可以使用 isMatch 来确定您拥有的字符串:

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 })
  );
}