-1

I have my ion-datetime input that gets the value of the user, also i have the varaible date that comes from a server, I want to compare them in a range, the thing is that when I get the value from the input, i get with the time fiels and not only the date, so when I use the method getTime(), it gets with the time and dont make a right comparision, any ideas to transform the date or reinitialise the time before i make the comparision?

This is my current method

ngOnInit() {
    this.desde = new Date(this.navParams.get('desde'));
    this.hasta = new Date(this.navParams.get('hasta'));
    this.auth.userData$.subscribe((res: any) => {
        this.authUser = res;
        this.postData = {token: this.authUser.token};
        if (this.postData) {
            this.planificadorService.planificadorData(this.postData).subscribe((res2: any) => {
                this.planificadorData = res2.planificadorData;
                this.planificadorData.forEach(item => {
                    if (item.fecha !== '') {
                        const fechaPlan = new Date(item.fecha);
                        if (fechaPlan.getTime() >= this.desde.getTime() && fechaPlan.getTime() <= this.hasta.getTime()) {
                            this.visblePLanificadorData.push(item);
                        }
                    }
                });
                console.log(this.visblePLanificadorData);
            });
        }

    });
}

Dates from inputs

desde: "2020-01-24T18:23:18.633-05:00"
hasta: "2020-01-27T18:23:18.634-05:00"

what should be

desde: "2020-01-24T00:00:00.000-00:00"
hasta: "2020-01-27T00:00:00.000-00:00"
Christian
  • 481
  • 1
  • 7
  • 24

2 Answers2

1

You can safely use the relational operators (>, <, <=, >=) to compare two dates in JavaScript. So, as you need to compare against a range I will use those.

The confusion sometimes came if you try to use the equality operators (==, ===, !=, !==), because this compare the "date instances" not "the date values".

If you want to "reset time", you can do this d2 = new Date(d).setHours(0,0,0,0); Mozilla Date.prototype.setHours() Doc.

Finally, there are many ways to achieve comparisons between javascript date, I recommend you to take a look at this post it have many of them including the things I mention Compare two dates with JavaScript

cabesuon
  • 4,860
  • 2
  • 15
  • 24
0

The aparent solution is to do this

new Date(this.desde.toDateString()).getTime()

and then compare, does anyone have an efficient way?

Christian
  • 481
  • 1
  • 7
  • 24