Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...