簡體   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