76

All, I'm using the jQuery UI for the date picker. I'm trying to check with javascript though that the date the user has entered is in the past. Here is my form code:

<input type="text" id="datepicker" name="event_date" class="datepicker">

Then how would I check this with Javascript to make sure it isn't a date in the past? Thanks

6 Answers 6

142

$('#datepicker').datepicker().change(evt => {
  var selectedDate = $('#datepicker').datepicker('getDate');
  var now = new Date();
  now.setHours(0,0,0,0);
  if (selectedDate < now) {
    console.log("Selected date is in the past");
  } else {
    console.log("Selected date is NOT in the past");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="datepicker" name="event_date" class="datepicker">

8
  • 7
    The one-liner: if ($('#datepicker').datepicker('getDate') < new Date) { ... }. Parentheses can be omitted when invoking a function with the new keyword. Nov 29, 2011 at 3:42
  • 5
    You can probably skip the now variable. by using (selectedDate.getTime() < Date.now()) Jul 12, 2013 at 15:05
  • @MiguelTrias: Of course. This makes it just a little bit clearer for the reader.
    – Amadan
    Jul 18, 2013 at 4:51
  • 3
    If you're just looking at the date (without time) then you should probably compare against the start of today like so var now = ( new Date() ).setHours(0,0,0,0); Jun 22, 2016 at 21:04
  • 2
    @IvanYurchenko: .val() returns a string, literally what's in the <input>. .datepicker('getDate') returns a Date object.
    – Amadan
    Jan 6, 2018 at 14:56
16
var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}
3

Simply convert the dates into milliseconds and subtract

let givenDate1 =   new Date("10/21/2001")  // Past Date
let givenDate2 =   new Date("10/21/2050") // future Date

If diff is positive, then given date is PAST

 let diff = new Date().getTime() - givenDate1.getTime();
  if (diff > 0) {
     console.log('Given Date givenDate1 is in Past');
   }

If diff is negative, then given date is Future

 let diff = new Date().getTime() - givenDate2.getTime();
  if (diff < 0) {
     console.log('Given Date givenDate2 is in Future');
   }
3
  • Do you really need new Date($.now()) ? isn't it the same with new Date() ? Feb 19, 2022 at 10:36
  • 1
    @AlexandruEftimie, yeah you are right, both are same. no need for doing new Date($.now()) Feb 19, 2022 at 17:37
  • +1. If you don't want to treat today as being in the past then instead of .getTime() you can use .setHours(0,0,0,0).
    – wkille
    Oct 6 at 6:55
2

To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.

// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};
Date.method('inPast', function () {
    return this < new Date($.now());// the $.now() requires jQuery
});

// including this prototype as using in example
Date.method('addDays', function (days) {
    var date = new Date(this);
    date.setDate(date.getDate() + (days));    
    return date;
});

If you dont like the safety check you can use the conventional way to define prototypes:

Date.prototype.inPast = function(){
    return this < new Date($.now());// the $.now() requires jQuery
}

Example Usage

var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
-2

You can use isPast(date) method from date-fns library.

import { isPast } from 'date-fns'
console.log(new Date('1991-06-17'));
// returns true.
console.log(new Date('2191-06-17'));
// returns false.

More info about the method: https://date-fns.org/v2.29.3/docs/isPast

-11
function isPrevDate() {
    alert("startDate is " + Startdate);
    if(Startdate.length != 0 && Startdate !='') {
        var start_date = Startdate.split('-');
        alert("Input date: "+ start_date);
        start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
        alert("start date arrray format " + start_date);
        var a = new Date(start_date);
        //alert("The date is a" +a);
        var today = new Date();
        var day = today.getDate();
        var mon = today.getMonth()+1;
        var year = today.getFullYear();
        today = (mon+"/"+day+"/"+year);
        //alert(today);
        var today = new Date(today);
        alert("Today: "+today.getTime());
        alert("a : "+a.getTime());
        if(today.getTime() > a.getTime() )
        {
            alert("Please select Start date in range");
            return false;
        } else {
            return true;
        }
    }
}
1
  • 1
    where comes the var Startdate from?
    – Jonathan
    Jun 18, 2015 at 11:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.