0

I created a checkbox in my template to hide all elements that have been taken place earlier than today depending on the bookingEnd in my JSON data. The recent-filter.pipe.ts pipe should filter all past events.

To my problem, I get an error TS2365: Operator '>' cannot be applied to types 'number' and 'Date'. in advance in the pipe and no data gets displayed on my template. The whole scenario works in pure JavaScript, so I think that bookingEnd is definitely a date object.

Can you help me why there is no data after applying the pipe filter?

JSON Data:

{
  bookingStart: "2019-10-27T23:00:00.000Z",
  bookingEnd: "2019-12-29T23:00:00.000Z",
  city: "Manhattan",
  confirmed: false,
  country: "UK"
}

recent-filter.pipe.ts:

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

@Pipe({
  name: 'recentFilter'
})
export class RecentFilterPipe implements PipeTransform {
  transform(list: any[], checked: boolean) {
    if (checked) {
      const futureDates = list.filter(x => {
        return Date.parse(x.bookingEnd) > new Date();
      });
      return futureDates;
    } else {
      return list;
    }
  }
}

bookings-table.component.html:

<tr
  *ngFor="
    let item of bookings
    | recentFilter: checked
  ">
      ...
</tr>
  • You should compare dates by getting the timestamp, ie `new Date().getTime()` So you can use bigger than and smaller than operators. – Frank Adrian Oct 25 '19 at 12:49

2 Answers2

0

Error you get already tells you not to use > to compare dates
To compare them use .getTime() method

new Date(x.bookingEnd).getTime() > new Date().getTime()
Buzzinga
  • 401
  • 3
  • 9
  • Thanks for helping out. But the returned objects are still empty. The error, it seems, is resolved! –  Oct 25 '19 at 14:35
0

The problem here seems to be that Date.Parse returns a number. The documentation says: Date.Parse (Dev Mozilla)

You should use new Date(Date.Parse([YOUR_STRING_DATE])); but I would advice you to be aware of wrong string formats and null values will date parsing.

It would be event better to avoid Date.Parse with a more modern syntax for parsing Date Parsing es6 and then compare them using the getTime() function Compare Dates es6

StPaulis
  • 2,844
  • 1
  • 14
  • 24