Rickus Harmse Rickus Harmse - 10 months ago 35
jQuery Question

jQuery check if start_date is bigger than end_date

I have the following problem.

I get a start_date and end_date from my HTML form, both dates are valid and are entered/selected by a bootstrap date picker.

An example of the dates are as follows

start_date = 15-06-2016
end_date = 14-06-2016

I have the following code to check if the start date is large than the end date:

if (Date.parse(start_date) > Date.parse(end_date))
error = true;
console.log('start date is greater than end date');
console.log('start date is smaller than end date');

start date is bigger than the end date, but in my validation, is always logs "start date is smaller than end date"

I also tried the following in my conditional statement, but still get the same results:

if (new Date(start_date) > new Date(end_date))
if (start.Date > date.Date)

if I switch the ">" with "<", I still get the same results. The statement always does the else statement.

I think the conversion from string to date might be the problem.

Thanks in advance


You can use String.prototype.split(), Array.prototype.reverse(), Array.prototype.join(), new Date(), .getTime()

var start_date = "15-06-2016"
, end_date = "14-06-2016";

function getTime(d) {
  return new Date(d.split("-").reverse().join("-")).getTime()

console.log(getTime(start_date) > getTime(end_date))