1

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!");
    } 
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

4 Answers4

4

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>
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
2

When comparing dates, always work with Date objects. The caveat with this is that when creating the objects, the provided date strings have to be in d/m/y or d-m-y format. Also note that today is not 16/10/2016.

jQuery(document).ready(function() {
  var datetodayvar = new Date();
  var deadlinadate = new Date('2/11/2016');

  if (datetodayvar >= deadlinadate) {
    console.log("yes!");
  } else {
    console.log("no!");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

First of all you are wrongly comparing two strings as if they were the numbers, when you do like this,

if(String(datetodayvar) >= String(deadlinadate)) { }

because if you want to compare strings you would have to

if(String(datetodayvar).equals(String(deadlinadate))){...

otherwise you compare the memory locations and not actual values. Read more What is the difference between == vs equals() in Java?

This code will check whether the two string objects are greater than or equal to each other alphabetically, and not according to your actual requirement of date comparision. The functional code would be like this:

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)) {
        console.log("yes!");          
    } else {
        console.log("no!");
    } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Community
  • 1
  • 1
kaushik gandhi
  • 768
  • 8
  • 14
0

Assuming date format as dd/mm/yyyy and that deadline >= today

var ar = '02/11/2016'.split('/').map(Number);
var valid = new Date(ar[2],ar[1]-1,ar[0]) >= new Date().setHours(0,0,0,0);

console.log(valid);
sabithpocker
  • 15,274
  • 1
  • 42
  • 75