Mr world wide
Mr world wide

Reputation: 4814

Date comparison validation in angular

I have 2 dates: 1.start and 2.end format is like this.

12/4/2017               console.log(startDate);
12/20/2017              console.log(endDate);

I am writing a validation to check if the end date is bigger than start date throw error,but it is not working. this is what i have tried:

var startDate = new Date(this.formB['startDateVal']).toLocaleDateString();
var endDate=new Date(this.formB['dueDateVal']).toLocaleDateString();

this is my condition:

if(endDate<startDate){
      this.bucketMsgClass='fielderror';
      this.bucketSuccessMsg = 'End Date is must lower than Start Date.';
 }

where am i doing wrong.?

Upvotes: 0

Views: 1687

Answers (2)

edo.n
edo.n

Reputation: 2410

I've always just subtracted one of the dates from the other. If the result is negative, then Date 1 is before Date 2.

var d1 = new Date("12/12/2017");
var d2 = new Date("12/13/2017");

console.log(d1 - d2) // -86400000 (exactly 1 day in milliseconds)

So

if (d1 - d2 < 0) {
    // d1 is smaller
}

Upvotes: 1

code.rookie
code.rookie

Reputation: 356

Going through this link that explains comparing dates in javascript would probably help you understand the problem and solve it.

Compare two dates with JavaScript

Upvotes: 1

Related Questions