0

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.?

2
  • 3
    You're comparing strings, instead of comparing dates. strings compare lexicographically, not chronologically. Commented Dec 8, 2017 at 7:19
  • It would help a lot if you told us what went wrong. Are we supposed to guess, and then help you? Commented Dec 8, 2017 at 7:21

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.