Check if date is in the past Javascript
Asked Answered
G

6

77

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

Gyniatrics answered 29/11, 2011 at 2:56 Comment(0)
C
143

$('#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">
Conformity answered 29/11, 2011 at 3:4 Comment(8)
The one-liner: if ($('#datepicker').datepicker('getDate') < new Date) { ... }. Parentheses can be omitted when invoking a function with the new keyword.Showcase
You can probably skip the now variable. by using (selectedDate.getTime() < Date.now())Atalaya
@MiguelTrias: Of course. This makes it just a little bit clearer for the reader.Conformity
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);Hudak
Why use setHours?Ethology
@Abhinav: explained by the comment immediately above yours: OP asked for "date", not "time".Conformity
Why can't we just use $('#datepicker').val() instead of $('#datepicker').datepicker('getDate')? Looks like it's working for me.Hinds
@IvanYurchenko: .val() returns a string, literally what's in the <input>. .datepicker('getDate') returns a Date object.Conformity
G
16
var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}
Gambrell answered 23/12, 2015 at 10:39 Comment(0)
P
4

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');
   }
Picro answered 1/10, 2021 at 14:33 Comment(3)
Do you really need new Date($.now()) ? isn't it the same with new Date() ?Providence
@AlexandruEftimie, yeah you are right, both are same. no need for doing new Date($.now())Picro
+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).Tumefacient
I
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());
Ivory answered 6/6, 2018 at 16:37 Comment(0)
A
-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

Algeria answered 20/9, 2022 at 14:40 Comment(0)
H
-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;
        }
    }
}
Hanselka answered 12/2, 2013 at 5:31 Comment(1)
where comes the var Startdate from?Edlun

© 2022 - 2024 — McMap. All rights reserved.