0

I have this two dates which I am getting through input field through javascript

var Date1 = document.nocAddition.Date1.value;
var Date2 = document.nocAddition.Date2.value;

I am trying to validate that Date 1 should always be more than date 2 and I am doing by the writing the below code:

var dateA = new Date(Date1);
var dateB = new Date(Date2);
if(Date.parse(dateA) < Date.parse(dateB)){
   alert('start is less than End');
   return false;
} else {
   alert('end is less than start');
   return false;
}

But the it is not matching the condition in loop and always alerting after else. Is there any new way to compare two dates through Javascript? Please help.

Amlan
  • 129
  • 1
  • 2
  • 14

2 Answers2

1

It's quite simple:

if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
    //your code here
}

Comparing 2 Date instances will work just fine. It'll just call valueOf implicitly, coercing the Date instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date instances will be coerced to the Number type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.

0
function compareDate(date1,date2){
    date1 = date1.split("-").reverse().join("-"); //formating 
    date2 = date2.split("-").reverse().join("-"); //formating 
    var oneDay = 24 * 60 * 60 * 1000;    
    var firstDate = new Date(date1);
    var secondDate = new Date(date2);
    return (Math.round((secondDate.getTime() - firstDate.getTime()) / (oneDay)) > 0);
}

example

// compareDate('2016-09-15','2016-09-17');

as formate

compareDate('15-11-2016','17-11-2015');
Mohammad
  • 21,175
  • 15
  • 55
  • 84
Nitya Kumar
  • 967
  • 8
  • 14