zarzou
zarzou

Reputation: 133

Compare between 2 dates variable in Angular

Can I compare between this 2 dates or do I need to convert one of them?

date1: 2019-07-31T23:00:00

date2: Fri Aug 30 2019 00:00:00 GMT+0100 (heure normale d’Afrique de l’Ouest)

I'm working with Angular

Upvotes: 0

Views: 148

Answers (3)

If you create a method,

compareDate(dateTimeOne: Date, dateTimeTwo: Date): YouReturn {
 if(dateTimeOne.getTime() > dateTimeTwo.getTime()) {
   ....
 }
}

If the variables are not date, you can try something like this

compareDate(dateTimeOne: string, dateTimeTwo: string): YouReturn {
     if(Date.parse(dateTimeOne) > Date.parse(dateTimeTwo)) {
       ....
     }
    }

You can too try this in moment js..

moment(Date1).format("YYYY-MM-DD") > moment(Date2).format("YYYY-MM-DD")

Upvotes: 0

arvind AK
arvind AK

Reputation: 51

if you are getting date dynamically from any-other source you can go with date pipe library in angular.

  var compare1=this.datepipe.transform(date,'dd/MM/yyyy');

  var compare2=this.datepipe.transform(date,'dd/MM/yyyy');

if (compare1 > compare2) {
   your code
}

Upvotes: 0

XardasLord
XardasLord

Reputation: 1947

Without using a 3rd party library, you can create new Date objects using both those formats and then simply use > comparer to compare them, like this:

const date1 = new Date("2019-07-31T23:00:00").getTime();
const date2 = new Date("Fri Aug 30 2019 00:00:00 GMT+0100").getTime();

if (this.date1 > this.date2) {
   //...
}

Upvotes: 3

Related Questions