开发者

Check the dates in JavaScript

开发者 https://www.devze.com 2023-04-01 19:05 出处:网络
I want to check two dates in java script. date format is YYYY-MM-dd. var date1 = 2开发者_如何学运维011-9-2;

I want to check two dates in java script. date format is YYYY-MM-dd.

var date1 = 2开发者_如何学运维011-9-2;
var date1 = 2011-17-06;

Can anybody say how can I write condition?


If you mean that you want to compare them and your variables are strings, just use == for comparison.

var date1 = '1990-26-01';
var date2 = '2000-01-05';

if (date1 == date2) {
   alert('date1 = date2')
}
else {
   alert('something went wrong');
}


There are four ways of instantiating dates

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Here is the link to complete tutorial and function of creating, comparing dates http://www.w3schools.com/js/js_obj_date.asp


If you want to compare dates , have a look at the JS date object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date , in particular the getTime() method .


Assuming the format is YYYY-MM-dd (your second date value breaks this rule) and that they are strings...

var date1 = '2011-9-2';
var date2 = '2011-06-17';

var fields = date1.split("-");
var d1 = new Date (fields[0], fields[1]-1, fields[2]);

var fields = date2.split("-");
var d2 = new Date (fields[0], fields[1]-1, fields[2]);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号