how to get data between the date range in javascript

I would like to know how to get data between date range in javascript

I have object array obj and variables sdate and edate,

how to get array object if the cdate falls between the range sdate and edate

function getdate(){
     var finals=[];
     var result = obj.orders.filter(e=>{
     if(e.cdate < sdate && e.cdate > edate){
       finals.push(e); 
     }
  })

}

var obj={
  orders:[
      {id:1, mode: "xyz", orderid: 123, cdate: "2017-2-13 07:33:30"},
      {id:2, mode: "abc", orderid: 456, cdate: "2018-4-20 06:10:30"},
      {id:3, mode: "xyz", orderid: 768, cdate: "2020-8-10 08:00:00"}
  ]
}

var sdate="11-5-2020"
var edate="20-2-2021"


Expected Output

[
  {id:3, mode: "xyz", orderid: 768, cdate: "2020-8-10 08:00:00"}
]

Answer

In your attemot you are comparing your sdate and edate with cdate node from the onjects in array. This will berform only string comparison, since both of them are strings. To perform Date comparison, you have to convert both of them into Date objects. Your cdate is a standard date object, so new Date() will retun the date object for the string.

But your sdate and edate are not valid date strings. So I have splitted them and created new date object using that. Comparing the date objects will provide you the expected result.

Also I have set hours of endDate to 23, 59, 59, 999. This is to ensure that if a date in array comes with the same date as end date, that should be filtered out. Because that is the maximum value for end date for the particular day.

Also you dont need to push finals.push(e) inside the filter function. Instead you could simply return the status of that comparison inside your filter. This will generate a new array. This will be your expected result.

Your logic for calculating the value inbetween two dates is wrong. i have corrected that aswell.

var sdate = "11-5-2020";
var edate = "20-2-2021";

var obj = {
  orders: [
    { id: 1, mode: "xyz", orderid: 123, cdate: "2017-2-13 07:33:30" },
    { id: 2, mode: "abc", orderid: 456, cdate: "2018-4-20 06:10:30" },
    { id: 3, mode: "xyz", orderid: 768, cdate: "2020-8-10 08:00:00" }
  ]
}

function getdate() {
  var finals = [];
  const [sDay, sMonth, sYear] = sdate.split('-');
  const [eDay, eMonth, eYear] = edate.split('-');
  const startDate = new Date(sYear, +sMonth - 1, sDay);
  const endDate = new Date(eYear, +eMonth - 1, eDay, 23, 59, 59, 999);
  var result = obj.orders.filter(e => (new Date(e.cdate) >= startDate && new Date(e.cdate) <= endDate));
  return result;
}

console.log(getdate());

Please Note You can perform string comparison with dates if they are in standard ISO format. If your want to make use of that, you need to make the start and end date to iso format and perfrom comparison. So the filter statement will be

var result = obj.orders.filter(e => e.cdate >= startDate.toISOString() && e.cdate <= endDate.toISOString());