Skip to content Skip to sidebar Skip to footer

Check If A Date Is Greater Than Specified Date

How can I check that a date is greater than or less than the specified date using javascript by passing the month and year only in MMM-YYYY Format. For example : Let the user selec

Solution 1:

Try this -

var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
console.log(+x > +y);
console.log(+x === +y);

Solution 2:

First convert it to date object

  // convert to a parseable date string:
   var dateStrA = "28/12/2013 16:20:22".replace( /(\d{2})\/(\d{2})\/(\d{4})/,        "$2/$1/$3");
    var dateStrB = "28/12/2013 16:20:11".replace( /(\d{2})\/(\d{2})\/(\d{4})/,        "$2/$1/$3");

     // now you can compare them using:
      new Date(dateStrA) > new Date(dateStrB);

Solution 3:

var date1 = Math.ceil(Math.abs(first date) / (1000 * 3600 * 24));
var date2 = Math.ceil(Math.abs(second date) / (1000 * 3600 * 24));
if(date1  > date2 )
   alert("date1");
else
   alert("date2");

Solution 4:

You just have to do a simple compare of dates. Please read more about "Date" here: http://www.w3schools.com/js/js_date_methods.asp

Maybe this code might help:

var day = 1; // Since you don't care about the day just use the first day
var month = session("month"); // Use the number of the month instead of the name
var year = session("yrs");
var dateJune = Date.parse("2016-07-01"); // June
var dateInput = Date.parse(year + "-" + month + "-" + day);
// Compare dates
if (dateJune > dateInput) {
    // The input is before june
} else if (dateJune < dateInput) {
    // The input is after june
} else {
    // It is june
}

You need a valid date format to be able to parse the date. Instead of getting "JUN" from your select box it would be better to get the number of the month instead. A select box should look like this:

<select>
<option value="01">Jan</option>
<option value="02">Feb</option>
...
</select>

If this is not an option you can use a function that calculates the number for you if you know then string values that your month variable might have:

function (nameOfMonth) {
   switch (nameOfMonth) {
     case 'Jan':
        return "01";
     case 'Feb':
        return "02";
     ....
   }
}

Post a Comment for "Check If A Date Is Greater Than Specified Date"