IndigoHollow IndigoHollow - 1 month ago 9
Javascript Question

Compare date and string with jquery

I'm trying to compare today date and the date from the string. They both has a string type. Why do I get "no!" ?

jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" +(((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}

datetodayvar = new Date().today();
deadlinadate = '16/10/2016';

if (String(datetodayvar) >= String(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
}
});

Answer

Turn them both to Date objects instead of strings.

jQuery(document).ready(function () {
    Date.prototype.today = function () { 
        return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
    }

    datetodayvar = new Date().today();
    deadlinadate = '02/11/2016';

    if(new Date(datetodayvar) >= new Date(deadlinadate)) {
        alert("yes!");          
    } else {
        alert("no!");
    } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you have your "date string" from 3 different input fields(dropdowns or whatever) don't input a string, but make the date format as follows.

var year = 2015;
var month = 2-1; // February
var day = 27;
var now = new Date(year, month, day);

That way, you don't have to worry about date notation, localisation, if you need to use a - a . or / or something else inbetween.

Also remember the month, is always -1 because it starts counting as 0(januari being 0, december being 11.

Also, keep mind of day light savings time. That might go hayward with your freshly minted date objects too by subtracting an hour.

The snippet below has all the things i'd use in a "simple" comparing mechanism.

jQuery(document).ready(function () {
        var str = '';
        for(var c=1;c<32;c++) {
            str += '<option value="'+c+'">'+c+'</option>';
        }
        $('#day').html(str);
        var str = '';
        for(var c=0;c<12;c++) {
            str += '<option value="'+c+'">'+(c+1)+'</option>';
        }
        $('#month').html(str);
        var str = '';
        for(var c=parseInt(new Date().getFullYear());c>1990;c--) {
            str += '<option value="'+c+'">'+c+'</option>';
        }
        $('#year').html(str);
        $('#istodaycheck').on('click',function() {
            var day = $('#day').get(0);
            var month = $('#month').get(0);
            var year = $('#year').get(0);
            
            var date = new Date(
                         year.options[year.selectedIndex].value,
                         month.options[month.selectedIndex].value,
                         day.options[day.selectedIndex].value);
            date.correctDst();
            
            $('#output').text(date.isToday() ? 'yes' : 'no');
        });
     });

/**
 * Retrieve standard timezome offset
 */ 
Date.prototype.stdTimezoneOffset = function() {
   var jan = new Date(this.getFullYear(), 0, 1);
   var jul = new Date(this.getFullYear(), 6, 1);
   return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/**
 * Checks if date is in day lights savings
 */
Date.prototype.dst = function() {
   return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
/**
 * corrects the unwanted substraction of an hour on fresh dates.
 */ 
Date.prototype.correctDst = function() {
    if(!this.dst()) {  
         this.setHours(this.getHours()+1);
     }
}
/**
 *  Returns a date instance without time components.
 */
Date.prototype.justDate = function() {
     var date = new Date(this.getFullYear(),this.getMonth(),this.getDate());
     date.correctDst();
     return date;
}
/**
 * Tests if given date is today.
 */
Date.prototype.isToday = function() {
    // strip possible time part.
    var testdate = this.justDate();          
    var datetodayvar = new Date().justDate();
    return datetodayvar.getTime() == testdate.getTime()
}
     
#output {
  background-color: #eee;
  border: 1px solid pink;
  display: block;
  width: 100%;
  height:200px;
  text-align: center;
  font-size:121pt;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="day">
</select>
<select id="month">
</select>
<select id="year">
</select>
<button id="istodaycheck">Is this date today?</button>
<div id="output">
</div>