0

I'm trying to do some error handling on an existing system. The backend can't be changed as it runs multiple systems. I'm working on moving the frontend from ASP.NET to React. I've come across a problem where I want to check if an array of objects contains a date, but the date retrieved from the backend comes as a /Date(1379282400000)/.

I've done some searches and can't find something that resembles this. I tried this code:

if (data.some(e => new Date(parseInt(e.Date.substr(6))).toDateString() === this.state.date.toDateString()) {
  // Logic
}

e.Date is the key used in the object for the dates and this.state.date is a date picked by the user. If I just do:

if (data.some(e => e.Date === "/Date(137982400000)/") {
  // Logic
}

as a test, then it works fine. So, it seems to be the converting of the date to the string that breaks the function, but can't understand how to fix it.

It would be nice to fix that it checks the date as doing .getTime() will not work as it could be the same date, but different times.

Akusas
  • 480
  • 1
  • 7
  • 27
  • This may be helpful: https://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format – kendaleiv Oct 19 '19 at 19:40
  • What are you putting in `this.state.date`? Take a look at the output of `toDateString`. Does that match the same format? Are you even comparing strings to strings, or does the state contain a `Date` object? – Matt Johnson-Pint Oct 19 '19 at 20:25
  • @MattJohnson-Pint ```this.state.date``` is a Date object which I change into a string. I tried running the ```.toDateString()``` as shown above, and did ```console.log()``` on both elements, could see that they returned the same, so seems like the parsing of the backend DateTime is breaking the ```.some()``` function – Akusas Oct 20 '19 at 06:35

1 Answers1

0

So, found out that the problem came from trying to convert the DateTime from the backend inside the .some() function, but I was able to work it out.

First I create a new array containing only the date as that was what I needed to run a check against:

const dateConvertion = data.map(function(elem) {
  return {
    date: new Date(parseInt(elem.Date.substr(6))).toDateString()
  };
});

Then I created the error handling:

if (dateConvertion.some(e => e.date === this.state.date) {
  // Error Handling
}
Akusas
  • 480
  • 1
  • 7
  • 27