0

I have an object that has an invalid date. I show this date in a table but I wanna say if the date is invalid then it should say "Future Date". My code is something like this:

for (let i = 0; i < res.data.length; i += 1) {
  if (!(res.data[i].inspectionDate instanceof Date &&
      !isNaN(res.data[i].inspectionDate))) {
    res.data[i].inspectionDate = 'Futre Date';
  }
}

but it still shows "Invalid Date" if the date is invalid. How can I display "Future Date" if the date is invalid?

Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
seyet
  • 1,080
  • 4
  • 23
  • 42
  • Does this answer your question? [Detecting an "invalid date" Date instance in JavaScript](https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript) – Evert Jul 22 '20 at 05:22
  • Because an invalid date object is still an instance of Date, so the `&&` condition fails. Change it to `||`. – RobG Jul 22 '20 at 09:24

3 Answers3

0

Use this

for (let i = 0; i < res.data.length; i++) {
    if (JSON.stringify(new Date(res.data[i].inspectionDate)) === 'null') {
        res.data[i].inspectionDate = "Futre Date";
    }
}
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
Hrishi
  • 1,210
  • 1
  • 13
  • 25
0

I don't understand why you have used !isNaN(res.data[i].inspectionDate). I think !(res.data[i].inspectionDate instanceof Date) this is enough to check is date is invalid or not. Please check below code.

var res = {
  data: [{
      inspectionDate: 'INVALID DATE'
    },
    {
      inspectionDate: new Date()
    }
  ]
};

for (let i = 0; i < res.data.length; i++) {
  if (!(res.data[i].inspectionDate instanceof Date)) {
    res.data[i].inspectionDate = 'Future Date';
  }
}

console.log(res);

You can also use this way.

var res = {
  data: [{
      inspectionDate: 'INVALID DATE'
    },
    {
      inspectionDate: new Date()
    }
  ]
};

res.data.forEach(data => {
  if (!(data.inspectionDate instanceof Date)) {
    data.inspectionDate = 'Future Date';
  }
});

console.log(res);
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
0

You only need to check if the Date can be coerced to a valid number:

if (isNaN(res.data[i].inspectionDate)) {
       res.data[i].inspectionDate = "Futre Date";
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80