Search code examples
javascriptmomentjsflatpickr

NaN while finding Difference using momentjs


I am using flatpickr to get date from the user. I am getting two dates from the user. Now I want to find the difference between two dates but its showing NaN. enter image description here

 computed: {
    total() {
      if (this.selectedRooms && this.selectedRooms.length) {
        const check_in = moment(this.form.check_in, "d-m-Y H:i");
        const check_out = moment(this.form.check_out, "d-m-Y H:i");

        const nights = check_in.diff(check_out, "days");
       
        let total = 0;
        for (let i = 0; i < this.selectedRooms.length; i++) {
          if (this.invoice.nights) {
            total += +this.selectedRooms[i][this.type] * +nights;
          } else {
            total += +this.selectedRooms[i][this.type];
          }
        }
        return total;
      } else {
        return 0;
      }
    }
}

Flatpickr config

 configdateTimePicker: {
        enableTime: true,
        dateFormat: "d-m-Y H:i",
      },

Error

NaN

When I try it without parsing dates it's showing me Invalid date


Solution

  • Formatting/parsing tokens are different in flatpickr and moment. So when parsing to moment object, you must follow moment formatting/parsing token

    const date1 = "25-08-2020 21:38"
    const date2 = "26-08-2020 21:38"
    const firstDate = moment(date1, "DD-MM-YYYY HH:mm")
    const secondDate = moment(date2, "DD-MM-YYYY HH:mm")
    
    console.log(firstDate.diff(secondDate, "days"))
    <script src="https://momentjs.com/downloads/moment.min.js"></script>