Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 : How to filter records between two dates?

{
 "id":1,
 "name":"Jack",
 "date":"01-06-2017"
},
{
 "id":2,
 "name":"Allen",
 "date":"07-08-2017"
},
{
 "id":3,
 "name":"Annie",
 "date":"22-11-2017"
},

This JSON stored in 'members' Array I want filter the member based on start and end date like:

 let startDate;
 let endDate;
 let selectedMembers = this.members.filter(m => m.date > startDate && m.date < endDate);

something like that..

like image 694
M Rameez Avatar asked Apr 20 '18 07:04

M Rameez


People also ask

How do you filter dates in arrays?

You can use the array_filter() function to filter multidimensional array by date range using PHP. This example will show you how to filter array by specific date range in PHP. The following code snippet helps to filter last month events from an array using the array_filter() and strtotime() function in PHP.

What are filters in angular 2?

Filter is an important part in AngularJS as well as Angular 2 or Angular 4. It is basically used to filter an item from a group of items, which are there in an array or an object array. It selects a subset of the items from an array and returns it as a new array and this item is displayed on UI.

Is date a filter in Angular JS?

AngularJS date filter is used to convert a date into a specified format. When the date format is not specified, the default date format is 'MMM d, yyyy'. Parameter Values: The date filter contains format and timezone parameters which is optional.


2 Answers

This is the solution of my problem:

members:any[] = [{
 "id":1,
 "name":"Jack",
 "date":"01-06-2017"
},
{
 "id":2,
 "name":"Allen",
 "date":"07-08-2017"
},
{
 "id":3,
 "name":"Annie",
 "date":"22-11-2017"
}];

let start = "01-02-2017";
let end = "06-07-2017";

let.selectedMembers = this.members.filter(
m => new Date(m.date) >= new Date(startDate) && new Date(m.date) <= new Date(endDate)
);

console.log(selectedMembers);
like image 52
M Rameez Avatar answered Sep 27 '22 19:09

M Rameez


u need first to transform the dates from string to Date type in order to compare them properly then do something like:

let members: any[] = [{
        "id": 1,
        "name": "Jack",
        "date": "01-06-2017" // this should be of object Date()
    },
    {
        "id": 2,
        "name": "Allen",
        "date": "07-08-2017" // this should be of object Date()
    },
    {
        "id": 3,
        "name": "Annie",
        "date": "22-11-2017" // this should be of object Date()
        }];

    let start = "01-02-2017;  // this should be of object Date()
    let end = "06-07-2017"; // this should be of object Date()

        let selectedMembers = members.filter(m => {
          if ( m.date > start && m.date < end) // or you can cast here to Date()
            return m;
    });

    console.log(selectedMembers);
like image 32
Allain Avatar answered Sep 27 '22 20:09

Allain