Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check date with current date using jQuery

I want to check my date is greater than current date

$("#EndDate").val() ="5/13/2014" ->M/d/y

Please find below code

if (Date.parse(new Date()) > Date.parse($("#EndDate").val())) { 

 //condition satisfied for today date too.

}

so my end date is today date.but still current date greater than end date. why ? how can i check and validate this. i understood some time value is greater than end date. but i want to check only date/month/year not time.

like image 458
SivaRajini Avatar asked May 13 '14 11:05

SivaRajini


2 Answers

Try as below:

var end_date    = "05/12/2014"
if(new Date() > new Date(end_date))
{   
 alert('End date should be greater than Start date');
}

fiddle

like image 42
Dave Avatar answered Sep 28 '22 15:09

Dave


If:

$("#EndDate").val();

returns a string in m/d/y format, you can turn that into a date object using:

function parseDate(s) {
  var b = s.split(/\D/);
  return new Date(b[2], --b[0], b[1]);
}

To create a comparable date, do what you are already doing:

var today = new Date();
today.setHours(0,0,0,0);

So now you can do:

if (parseDate($("#EndDate").val()) > today) {
  // date is greater than today
}

or if you really must:

if (+parseDate($("#EndDate").val()) > new Date().setHours(0,0,0,0)) ...

Please note that when you do:

Date.parse(new Date().setHours(0, 0, 0, 0))

firstly a new date is created from new Date(). Calling setHours() sets the time value, but the return value from the call is the UTC time value of the Date object.

Date.parse expects a string that looks something like a date and time, so if you pass it a number time value something like 1399903200000, the implementation will fall back to some implementation heuristics to either turn it into a Date or NaN.

So please don't do that. Parsing any string with Date.parse is implementation dependent (even the strings specified in ECMA5) and will return different results in different browsers. So please don't do that either.

like image 178
RobG Avatar answered Sep 28 '22 13:09

RobG