Search code examples
javascriptreactjsmomentjsdate-fns

Convert moment.js to date-fns


I need to convert this from moment.js moment(date, 'DD MM YYYY').isBefore(moment()) to date-fns. I tried isBefore(format(value, 'dd-MM-yyyy'), sub(new Date(), { days: 1 })). I mention that now I have to substract 1 day. So the functionality will be to compare value which is the date given with currentDate - 1 day. Essentially, check if future date is given, (future date includes current day). Hope this is clear enough. My example doesn't work and I don't understand why.


Solution

  • Looks like you're using format instead of parse. isBefore accepts a number or Date not a string as its first argument.

    See 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');
    console.log(test);
    

    As requested in comments

    We can run the value against a function that replaces all / and \s to -.

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