Home > Software engineering >  How can I filter data according to date now in Angular Typescript?
How can I filter data according to date now in Angular Typescript?

Time:12-22

I have bookings and I want to get all completed bookings that passed (bookings that's < date now)

I tried to filter bookings by checkout attribute according to date now but didn't work it always display all my booking list.

This is my Reservation model:

export class Reservation {
  id!: number;
  nb!: number;
  montantTotal!: number;
  user!: User;
  extra!: number;
  couponon!: number;
  nbrooms!: number;
  montantExtraRoom!: number
  dateCreated!: Date
  vol!: Vol;
  checkin!: Date;
  checkout!: Date;
  persones: Persone[] = [{
    titre:'',
    firstname:'',
    lastname:'',
    datebirth:'',
    nationality:'',
    passport:0,
    country:'',
    passworddateout:'',
  }]
}

And this is my component:

export class UserMybookingComponent implements OnInit {
  myres!: Reservation[]
  myDate = new Date();

  constructor(private reservationService: ReservationService, private datePipe: DatePipe ) { 

  }
  
  ngOnInit() {
    this.mybooking()
   
  }

  mybooking(){
    
    this.reservationService.mybook().subscribe(
      data => {this.myres=data;
        this.myres.filter(res => new Date(res.checkout) > this.myDate)
      }
      
    )
  }
}

CodePudding user response:

Write

this.myres = this.myres.filter(res => new Date(res.checkout) > this.myDate);

You forgot this.myres = ;

https://www.tutorialspoint.com/typescript/typescript_array_filter.htm

CodePudding user response:

If you want to display the data try this

displayDate: any;

mybooking(){

this.reservationService.mybook().subscribe(
  data => {this.myres=data;
    this.myres.filter(res => new Date(res.checkout) > this.myDate)

 this.displayDate = res;
  }
  
)
}

put this in your html file

{{displayDate?."index of the element you want to display goes here" | date:'fullDate'}}

CodePudding user response:

please always use getTime() or valueOf() for accurate comparison of Dates(in milliseconds)

new Date(res.checkout).getTime() > this.myDate.getTime()
  • Related