I have created a little StackBlitz-Project that represents my situation. I want to log all objects within a chosen date range. But when I filter my object I get a empty array as results. I wanted to ask you how to compare dates, because depending on which datepicker you have you get a different value from the datepicker. It also depends on in which format you store the date (in this case a string).
Could you help me with my simple example? https://stackblitz.com/edit/angular-hbqguu
EDIT: I created an array:
public obj = [{
name: "jan",
date: "20.03.2010"
},{
name: "ion",
date: "10.01.2003"
},{
name: "caesar",
date: "01.02.2009"
},{
name: "chris",
date: "17.03.2015"
}]
and I am trying to filter the objects with a certain date of the format 'DD.MM.YY' as you can see. Therefore I created to functions for two different inputs of type date.
<div>
<p>Filtering by date range</p>
<input type="date" (change)="changeFirstInput($event)"> -
<input type="date" (change)="changeSecondInput($event)">
<span>
<ul>
<ng-container *ngFor="let o of obj">
<li> {{o.name}} {{o.date}}</li>
</ng-container>
</ul>
</span>
</div>
Filter functions
public date1: Date = new Date("2000-01-01");
public date2: Date = new Date();
changeFirstInput(e){
this.date1 = e.target.value;
console.log(this.obj.filter(o => new Date(o.date) >= this.date1 &&
new Date(o.date) <= this.date2 ));
}
changeSecondInput(e){
this.date2 = e.target.value;
console.log(this.obj.filter(o => new Date(o.date) >= this.date1 &&
new Date(o.date) <= this.date2 ));
}
My filter function returns an empty array []
. I am not really sure how to compare dates, I guess it depends on all formats you have as mentioned above.