Home > Back-end >  How to check if date equals today's date in component template
How to check if date equals today's date in component template

Time:06-23

I'm showing a list of news on the page and want to print word "Today" if news date is equals to today's date otherwise print the full date on the page. Are there any ways to compare news.Date to todaysDate in template somehow?

On template:

<ng-container *ngFor="let news of data">
 <*ngIf="news.Date === todaysDate; else showDate">
   <time > 
     Today
   </time>

<ng-template #showDate>
 <time >
    {{ news.Date | dateFormat: 'dd.MM.yyyy H:mm'}}
 </time>
</ng-template>
</ng-container>

Getting today's data todaysDate in Angular component:

const todaysDate = formatDate(new Date(), 'yyyy.MM.dd', 'en')

CodePudding user response:

This is probably due to a conflict in date formats, to overcome this problem use a function that standardize the date such as toDateString(), here's a sample code for your use case

// TS
isToday(date: Date | string): boolean {
    return new Date().toDateString() === new Date(date).toDateString();
}

And corresponding template becomes

// HTML
<ng-container *ngFor="let news of data">
  <ng-template *ngIf="isToday(news.date); else showDate">
    <time >
      Today
    </time>
  </ng-template>
  <ng-template #showDate>
    <time >
      {{ news.Date | dateFormat: 'dd.MM.yyyy H:mm'}}
    </time>
  </ng-template>
</ng-container>

CodePudding user response:

You can add a new Angular Pipe that does this for you:

today-or-not-today.ts

import { Pipe, PipeTransform } from '@angular/core';
import {formatDate} from "@angular/common";

@Pipe({
  name: 'todayOrNotToday'
})
export class TodayOrNotTodayPipe implements PipeTransform {

  transform(value: Date, ...args: unknown[]): string {
    let today: string = formatDate(new Date(), 'yyyy.MM.dd', 'en');
    let givenDate: string = formatDate(value, 'yyyy.MM.dd', 'en');
    if (givenDate == today){
      return "Today";
    }else{
      return givenDate;
    }
  }
}

And use it in your HTML like this:

{{ someDate | todayOrNotToday }}
  • Related