0

I am facing an issue with javascript dates. I want to comparing start date and end date JSON data and show in specific slot newprevious, newcurrent, newfirstdate and newseconddate

react component

i tried but my condition is not working

        <div class="row">
          {this.state.data && this.state.data.length
            ? // this.state.data[index].start_date.toString() > this.state.newprevious
              // this.state.data[index].start_date.toString() > this.state.newcurrent
              // this.state.data[index].start_date.toString() > this.state.newfirstdate
              // this.state.data[index].start_date.toString() > this.state.newseconddate
              this.state.data.map(
                ({ cust_full_name, full_name, start_date }, index) => (
                  <div class="row" key={index}>
                    slot: {index + 1}
                    <p>{start_date}</p>
                    <p>{cust_full_name}</p>
                  </div>

My working demo:

https://codesandbox.io/s/priceless-bird-ue3iu?file=/src/App.js

my code output:

enter image description here

just match start date and end date JSON data and show in specific previous , current , first and second date slot

expected output:

enter image description here

what i should do? please help me out?

MHasan
  • 69
  • 1
  • 8
  • Be careful of answers suggesting converting the string to a Date. "2020-05-11 01:45:50" is not a format supported by ECMA-262 so parsing is implementation dependent, at least one current browser will parse it as an invalid date. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 11 '20 at 00:21

3 Answers3

0

Assumption

Your dates inside this.state.data are in correct date format.

Solution

You can compare two dates in JavaScript by simply enclosing them in Date().

var date1, date2;
date1 = new Date("put ur date here to compare");
date2 = new Date("Dec 15, 2014 21:20:15" ); 
if (date1 > date2) {
 alert("Date1 is the recent date.");
 } 
else { 
alert("Date 2 is the recent date."); 
}
Community
  • 1
  • 1
Aditya Patnaik
  • 1,490
  • 17
  • 27
0

You could use Array.filter to remove all the items that don't pass the check and render only those that do.

Also, if you want to compare dates, you should do the following:

const prev = "2020-05-11 01:45:50";
const second = "2020-05-11 03:15:50";

// read why it needs to be normalized
// https://stackoverflow.com/a/45152231
const normalize = (value) => {
  return value.replace(/ /g, "T") + "Z"
}

// excluding `min` and `max`
const isBetween = (date) => {
  const min = new Date(normalize(prev))
  const max = new Date(normalize(second))
  const dateToCompare = new Date(normalize(date))
  
  return min < dateToCompare && dateToCompare < max;
}

console.log("2020-05-11 01:00:00", isBetween("2020-05-11 01:00:00"));
console.log("2020-05-11 02:45:00", isBetween("2020-05-11 02:45:00"));

Here's how you could go about this:

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      newprevious: ["2020-05-11 01:45:50"],
      newseconddate: ["2020-05-11 03:15:50"],

      data: [
        {
          id: "1",
          start_date: "2020-05-11 03:45:00",
          end_date: "2020-05-11 04:00:00",
          cust_full_name: "furqan"
        },
        {
          id: "2",
          start_date: "2020-05-11 02:45:00",
          end_date: "2020-05-11 03:00:00",
          cust_full_name: "ahmed"
        },
        {
          id: "3",
          start_date: "2020-05-11 02:30:00",
          end_date: "2020-05-11 02:45:00",
          cust_full_name: "ali"
        },
        {
          id: "3",
          start_date: "2020-05-11 01:00:00",
          end_date: "2020-05-11 01:15:00",
          cust_full_name: "mubeem"
        }
      ]
    };
  }

  render() {
    const { data, newprevious, newseconddate } = this.state;
    const filtered =
      data && data.length
        ? data.filter(({ start_date }) => {
            // normalize b/c `Safari` doesn't recognize this format as a proper date
            // see: https://stackoverflow.com/a/45152231
            const normalize = val => val.replace(/ /g, "T") + "Z";

            const min = new Date(normalize(newprevious[0]));
            const max = new Date(normalize(newseconddate[0]));
            const itemDate = new Date(normalize(start_date));

            return min < itemDate && itemDate < max;
          })
        : [];
    return (
      <div className="App">
        <div className="row">
          <p>{this.state.newprevious}</p>
          <p>{this.state.newseconddate}</p>
          <hr />
          {filtered.map(({ cust_full_name, start_date }, index) => (
            <div className="row" key={index}>
              slot: {index + 1}
              <p>{start_date}</p>
              <p>{cust_full_name}</p>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Here's an example of how to group items in different time slots as per OP's edit:

const data = [
  {
    id: "1",
    start_date: "2020-05-11 03:45:00",
    end_date: "2020-05-11 04:00:00",
    cust_full_name: "furqan"
  },
  {
    id: "2",
    start_date: "2020-05-11 02:45:00",
    end_date: "2020-05-11 03:00:00",
    cust_full_name: "ahmed"
  },
  {
    id: "3",
    start_date: "2020-05-11 02:30:00",
    end_date: "2020-05-11 02:45:00",
    cust_full_name: "ali"
  },
  {
    id: "3",
    start_date: "2020-05-11 01:00:00",
    end_date: "2020-05-11 01:15:00",
    cust_full_name: "mubeem"
  }
];

const prev = "2020-05-11 01:45:50";
const curr = "2020-05-11 02:15:50";
const first = "2020-05-11 02:45:50";
const second = "2020-05-11 03:15:50";
const dates = [prev, curr, first, second];

const result = dates.reduce((accumulator, date, idx, collection) => {
  if (idx === collection.length - 1) {
    return accumulator;
  }
  const min = new Date(normalize(date));
  const max = new Date(normalize(collection[idx + 1]));
  const foundItemWithDateBetween = findItemWithDateBetween(min, max, data);

  if (!foundItemWithDateBetween) {
    return accumulator;
  }
  return {
    ...accumulator,
    [idx]: {
      min: date,
      max: collection[idx + 1],
      item: foundItemWithDateBetween
    }
  };
}, {});

console.log("result", result);

function normalize(value) {
  return value.replace(/ /g, "T") + "Z";
}
function findItemWithDateBetween(min, max, items) {
  return items.find(({ start_date, end_date }) => {
    const startDate = new Date(normalize(start_date));
    const endDate = new Date(normalize(end_date));
    return min < startDate && endDate < max;
  });
}
goto
  • 4,336
  • 15
  • 20
  • ok i try your code [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 21:41
  • thanks one more thing i ask? [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 22:02
  • @MHasan yeah sure – goto May 10 '20 at 22:03
  • how should i compare `previous , current , first and second date` comparing with `start and end date`. [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 22:08
  • i have updated the `sandbox code` you can check [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 22:09
  • @MHasan not sure I follow, are you comparing `start_date` with `newprevious` and `newcurrent` **AND** `end_date` with `newfirstdate` and `newseconddate`? What is the exact comparison? – goto May 10 '20 at 22:11
  • i added a photo you can check [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 22:18
  • just match `start date and end date` and show in specific `previous , current , first and second date` slot [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 22:19
  • have you understand? i also added `expected output` [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 10 '20 at 22:21
  • @MHasan it'd be helpful if you provided the same exact data that you're showing in the expected output, but checkout my edit if you want to see how to group these items into different categories - there's only one item because that's the only one that matches. – goto May 10 '20 at 23:00
  • thanks ok let me check [@](https://stackoverflow.com/users/5862900/goto1) – MHasan May 11 '20 at 04:08
-1

I have adapted to your solution using new Date() from JS library. You can check out the solution.

Ehsan Mahmud
  • 725
  • 4
  • 11
  • ok i try your code [@](https://stackoverflow.com/users/7999155/ehsan-mahmud) – MHasan May 10 '20 at 21:44
  • thanks one more thing i ask? [@](https://stackoverflow.com/users/7999155/ehsan-mahmud) – MHasan May 10 '20 at 21:58
  • An answer should explain why the OP has their issue and how your code fixes it. You should post code here, not elsewhere. – RobG May 11 '20 at 01:46
  • It's a react code, I wanted to show what the end result looks like. And I proposed a solution. The OP didn't have an issue, he didn't know how to proceed. – Ehsan Mahmud May 11 '20 at 01:50