0

In a date picker I want to restrict input to prevent dates in the past. I used the JavaScript below but it's failing in certain conditions.

 function isPastDate(value) {
        var now = new Date;
        var target = new Date(value);

        if (target.getFullYear() < now.getFullYear()) {
            return true;
        } else if (target.getMonth() < now.getMonth()) {
            return true;
        } else if (target.getDate() < now.getDate()) {
            return true;
        }
    return false;
}

Can someone help me?

James Orr
  • 5,005
  • 7
  • 39
  • 63
Ryder
  • 514
  • 1
  • 7
  • 27

3 Answers3

4

As epascarello stated, simply compare both dates:

function isPastDate(value) {
    return new Date() > new Date(value);
}

This happens because the date is measured in milliseconds since Jan 1st 1970 (correct me if I'm wrong), so what is really happening is a comparison between two long numbers.

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • If you want to use this at a later time you could use a time stamp. If not, this method works fine. See [this post](http://stackoverflow.com/questions/11893083/convert-normal-date-to-unix-timestamp) for JavaScript time stamps. – Marvin Brouwer Feb 19 '14 at 15:04
1

See this post:

var selectedDate = $('#datepicker').datepicker('getDate');
var now = new Date();
if (selectedDate < now) {
  // selected date is in the past
}
Community
  • 1
  • 1
danielmhanover
  • 3,094
  • 4
  • 35
  • 51
-1

Your function is logically wrong, and doesn't check after if the years are actually the same before testing the months, same goes to months and days. You can try:

   function isPastDate(value) {
    var now = new Date;
    var target = new Date(value);

    if (target.getFullYear() < now.getFullYear()) {
        return true;
    } else if (target.getFullYear() === now.getFullYear())
        if (target.getMonth() < now.getMonth()) {
            return true;
        } else if (target.getMonth() === now.getMonth()) {
            if (target.getDate() < now.getDate()) {
                return true;
            }
        }
    }

    return false;
}

Hope that helps