how to filter array of objects based upon timestamp

前端 未结 2 1252
天涯浪人
天涯浪人 2021-01-07 03:16

I have more than 1 thousand array of objects and every object inside the array contains date and time fileds. This records are inserted to DB for every seconds as shown be

2条回答
  •  悲哀的现实
    2021-01-07 03:36

    You can use the filter as below to achieve this.

    data.filter((d) => {
      return new Date(d.date).getTime() >= seventhDay.getTime();
    });
    

    Here, if your date data type is Date already, you don't need to convert to date again new Date(d.date).

    Also, it will work without getTime() as below.

    return new Date(d.date) >= seventhDay;
    

    var data=[{"date":"11/20/2016 08:45:58","energy":29940913188,"power":6783,"time":217781102},{"date":"11/25/2016 08:46:01","energy":29940913267,"power":6792,"time":217781105},{"date":"11/25/2016 08:46:02","energy":29940913318,"power":6791,"time":217781107},{"date":"11/25/2016 08:46:04","energy":29940913344,"power":6797,"time":217781108},{"date":"11/25/2016 08:46:05","energy":29940913396,"power":6816,"time":217781110},{"date":"11/25/2016 08:46:07","energy":29940913421,"power":6798,"time":217781111},{"date":"11/21/2016 08:46:08","energy":29940913473,"power":6804,"time":217781113}]
    
    var seventhDay = new Date();
    seventhDay.setDate(seventhDay.getDate() - 7);
    
    var filteredData = data.filter((d) => {
      return new Date(d.date).getTime() >= seventhDay.getTime();
    });
    
    console.log(filteredData);

提交回复
热议问题