In my Angular program, I'm trying to filter an array based on if each of the dates are between 2 set dates. I have the dates set to be the first and the last of the current month:
StartDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
EndDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 0);
I have the user choose which days they would like to see the results of the array for:
<div class="col-sm-12" style="padding-left: 0px; text-align: center; padding-bottom: 10px;">
<label class="col-sm-5" style="text-align: right;">Start Date</label>
<div class="col-sm-7">
<input class="form-control" type="date" id="StartDate" [ngModel]="StartDate | date: 'yyyy-MM-dd'" (ngModelChange)="StartDate=$event" name="StartDate" />
</div>
</div>
<div class="col-sm-12" style="padding-left: 0px; text-align: center;">
<label class="col-sm-5" style="text-align: right;">End Date</label>
<div class="col-sm-7">
<input class="form-control" type="date" id="EndDate" [ngModel]="EndDate | date: 'yyyy-MM-dd'" (ngModelChange)="EndDate=$event" name="EndDate" />
</div>
</div>
</div>
and then, I call a function that filters the array based on those dates:
setValues(): void {
this.datePTO = this.ptoData.filter(pto => pto.date > this.StartDate && pto.date < this.EndDate);
}
If the user keeps the dates the same and then tries to see the array, it won't have anything in it. Whereas, if they change the dates at all, the array will fill with what should be in it. I've found out that whenever the user changes the dates, they change to string and then are compared somehow. How can I fix this so that they can just hit the button if the date range they want is the default one shown?
pto.date, is that a string or a date?startDateandendDate, they become strings, are compared withpto.dateand the correct array is printed. It just doesn't work for the default values for some reason. I tried converting them to strings and then comparing but I get an error where it says I can't compare a date (pto.date) to a string (startDateorendDate)pto.dateis aDate? Have you tried printingtypeof pto.date? Seems really wierd that it works when the user sets the date(as a String), but not when you convert them initially. Its also weird that the between comparison works with string and date types. Date is converted to number before comparison(.valueOf()), and a string compared to a number(<, >, ==, ===) always returnsfalse.console.logand they all printed out as strings. But, if I change my filter to bethis.datePTO = this.ptoData.filter(pto => pto.date > this.StartDate.toDateString()or.toString, it says "Operator '>' cannot be applied to types 'Date' and 'string'.".toISOString()when you first declareStartDateandEndDate. Wait, why does give that error with the.toString()on? does that mean the compiler thinkpto.dateis aDatebut it actually isn't? Or maybe I'm just confusing myself atm.