繁体   English   中英

将 moment.js 转换为 date-fns

[英]Convert moment.js to date-fns

我需要将它从 moment.js moment(date, 'DD MM YYYY').isBefore(moment())转换为 date-fns。 我试过isBefore(format(value, 'dd-MM-yyyy'), sub(new Date(), { days: 1 })) 我提到现在我必须减去 1 天。 因此,功能将是比较与 currentDate - 1 天给出的日期的value 本质上,检查是否给出了未来日期(未来日期包括当天)。 希望这足够清楚。 我的例子不起作用,我不明白为什么。

看起来您使用的是format而不是parse isBefore接受numberDate而不是字符串作为其第一个参数。

参见示例:

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

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

根据评论中的要求

我们可以针对将所有/\s替换为-的 function 运行该值。

function unifyDateString(value: string) {
  try {
    return value.split("/").join("-").split(" ").join("-");
  } catch {
    return value;
  }
}

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

const one = compareDate("31-12-2020");
const two = compareDate("31/12/2020");
const three = compareDate("31 12 2020");

console.log(one);
console.log(two);
console.log(three);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM