Reputation: 876
I am trying to compare dates in my app using ngIf, but I haven't been able to get it working properly so far.
<div *ngIf="(todaysdate | date:'MMM dd' == duedate | date:'MMM dd')">
List
</div>
I want to compare them using the date pipe because times on the full date string are different I only want to compare the dates. Any suggestions on how to properly do this are much appreciated.
Upvotes: 6
Views: 10503
Reputation: 551
A little extra but this is what I did based off the answer to compare expiration dates. Also, "expireDate" came as an object to I couldn't simply compare by two date objects.
.ts
today = new Date();
.html
<div *ngIf="(expireDate | date: 'yMMdd') > (today | date: 'yMMdd'); else template_Expired">
{{ expireDate | date }}
</div>
<ng-template #template_Expired>
<div class="expired">
{{ expireDate | date }}
</div>
</ng-template>
.css
.expired {
font-weight: bold;
color: red;
}
Upvotes: 1
Reputation: 500
Compare works fine when you format your dates properly (eg. 20191224 for christmas). So this should work
<div *ngIf="(todaysdate | date:'yMMdd' == duedate | date:'yMMdd')">
List
</div>
Upvotes: 6
Reputation: 4773
The quickest solution is to this.todaysdate.setHours(0, 0, 0, 0);
which you would do on your date prior in your constructor.
But you can also send it to and expression on the component *ngIf="compareDates()"
compareDates(){
return this.todaysdate.setHours(0, 0, 0, 0) == this.duedate.setHours(0, 0, 0, 0);
}
Upvotes: 1