75

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

mu is too short
  • 426,620
  • 70
  • 833
  • 800
user1048676
  • 9,756
  • 26
  • 83
  • 120

6 Answers6

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">
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 7
    The one-liner: `if ($('#datepicker').datepicker('getDate') < new Date) { ... }`. Parentheses can be omitted when invoking a function with the `new` keyword. – davidchambers Nov 29 '11 at 03:42
  • 5
    You can probably skip the ```now``` variable. by using ```(selectedDate.getTime() < Date.now())``` – Miguel Trias Jul 12 '13 at 15:05
  • @MiguelTrias: Of course. This makes it just a little bit clearer for the reader. – Amadan Jul 18 '13 at 04: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);` – Joshua Pinter Jun 22 '16 at 21:04
  • Why use setHours? – Abhinav May 15 '17 at 09:05
  • @Abhinav: explained by the comment immediately above yours: OP asked for "date", not "time". – Amadan May 15 '17 at 12:38
  • Why can't we just use `$('#datepicker').val()` instead of `$('#datepicker').datepicker('getDate')`? Looks like it's working for me. – Ivan Yurchenko Jan 05 '18 at 17:07
  • 2
    @IvanYurchenko: `.val()` returns a string, literally what's in the ``. `.datepicker('getDate')` returns a `Date` object. – Amadan Jan 06 '18 at 14:56
16
var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}
Leistungsabfall
  • 6,368
  • 7
  • 33
  • 41
Srinivasan S
  • 169
  • 1
  • 3
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());
Mike
  • 1,525
  • 1
  • 14
  • 11
2

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');
   }
mabdullahse
  • 3,474
  • 25
  • 23
-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

Matt Walterspieler
  • 2,073
  • 2
  • 21
  • 34
-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;
        }
    }
}
Vignesh
  • 1,458
  • 12
  • 31
  • 59