Skip to content Skip to sidebar Skip to footer

Check The Dates In JavaScript

I want to check two dates in java script. date format is YYYY-MM-dd. var date1 = 2011-9-2; var date1 = 2011-17-06; Can anybody say how can I write condition?

Solution 1:

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');
}

Solution 2:

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


Solution 3:

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 .


Solution 4:

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]);

Post a Comment for "Check The Dates In JavaScript"