likeGreen
likeGreen

Reputation: 1079

Sorting date using moment angular is not working

I have a method to sortDate which is called in Angular ts file.

import * as moment from 'moment';     
sortDate(a,b){
        const dateIsAfter = moment(a).isAfter(moment(b));
        const dateIsSame = moment(a).isSame(moment(b));
        const dateIsBefore = moment(a).isBefore(moment(b));
        if(dateIsAfter) {
          console.log('Input Date 1 :',a, ' Input Date 2: ',b ,' Returned dateIsAfter:',-1 * this.sortOrder );
          return -1 * this.sortOrder;
        }else if(dateIsBefore) {
          console.log('Input Date 1 :',a, ' Input Date 2: ',b ,' Returned dateIsBefore:',1 * this.sortOrder );
          return 1 * this.sortOrder;
        }else{
          return 0 * this.sortOrder;
        }
      }

The sortDate method is called:

this.sortDate(new Date(a[column]), new Date(b[column]));

My output in console: enter image description here

Sorting works perfectly fine for year 2021. But, when trying to verify with 2022 as highlighted Oct 08 2021 should come after Mar 2022. But, it returns First dateisAfter which is incorrect, as a result Mar 2022 which should be above, goes down. Again, everything in Mar 2022 is sorted perfectly fine. Why is this behaviour.

enter image description here

When using below sortDate() method it works fine in chrome. However it's not working in firefox

sortDate(a,b){
       return new Date(a).getTime() - new Date(b).getTime()
}

Output in chrome: enter image description here

Output on firefox:

enter image description here

Upvotes: 0

Views: 520

Answers (1)

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

what is the reason of using moment if you can just compare the dates by transforming them into milliseconds:

sortDate(a,b){
// or  return new Date(b).getTime() - new Date(a).getTime()
       return new Date(a).getTime() - new Date(b).getTime()
}

const dates = [ '03-MAR-2022 13:40:00', '02-MAR-2022 10:21:37', '31-DEC-2021 18:00:00', '31-DEC-2021 18:00:00', '31-DEC-2021 17:03:00', '31-DEC-2021 17:01:02', '31-DEC-2021 17:01:01', '31-DEC-2021 17:00:00', '08-OCT-2021 17:00:00', '08-NOV-2021 17:00:00', '22-DEC-2021 17:00:00', '30-DEC-2021 17:00:00'];

function sortDate(a,b){
    return new Date(b).getTime() - new Date(a).getTime()
    // or return new Date(a).getTime() - new Date(b).getTime()
}

dates.sort(sortDate);

console.log(dates);

How @MikeOne mentioned, it is not a good choice as it is deprecated, so avoid to use it in the comming projects

Upvotes: 2

Related Questions