Search code examples
angularangular6angular-pipe

how to compare dates with angular Pipe?


Why doesn't this filter work?

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

@Pipe({
  name: 'inProcess'
})
export class InProcessPipe implements PipeTransform {

  transform(events: any): any {
    if (!events) return events
    return events.filter(function (event) {
      return event.dateStart < Date.now();
    })
  }

}

this is where I tried to use the Pipe, I want to bring all Events that are late, < than the Date.now(), the property dateStart is a String value in my backend with express and mongoose, but it is saved as Datefrom the front end, so how I can do that?

   <h2 class="text-left text-muted title-margin-top title-style">Late</h2>
    <div *ngFor="let event of events | inProcess">
      <div *ngIf="event.isCompleted === true">
        <div class="card">
      <div class="row">
        <div class="container">
          <div class="single-event col-md-10 col-md-offset-1">
            <div class="event-name">
              <a [routerLink]="['/event', event._id]">
                <h3>{{event.name}}</h3>
              </a>
            </div>
            <p>
              <span class="glyphicon glyphicon-file"></span>
              obra: {{ event.section.name}}
            </p>
            <p>
              <span class="glyphicon glyphicon-time"></span>
              publicado en: {{ event.created_at | date: 'dd / MM / yyyy' }}
            </p>

            <hr>

            <div class="row">
              <div class="container">
                <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
                  <p class="card-text CardInfo text-center">Fecha Inicio</p>
                  <div class="text-center">
                    {{ event.dateStart | date: 'dd-MM-yyyy' }}
                    <hr class="style1">
                  </div>
                </div>

Solution

  • The compare you have will always return false. Try to parse the string first before comparing timestamp like this:

      transform(events: any): any {
       if (!events) return events
        return events.filter(function (event) {
         return Date.parse(event.dateStart) < Date.now();
       })
     }