Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if date is in the past Javascript

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

like image 680
user1048676 Avatar asked Nov 29 '11 02:11

user1048676


People also ask

How do you know if a date is past?

const dateInPast = function(firstDate, secondDate) { if(firstDate. setHours(0,0,0,0) <= secondDate. setHours(0,0,0,0)) { return true; } return false; } const past = new Date('2020-05-20'); const today = new Date(); const future = new Date('2030-05-20'); console. log(dateInPast(past, today)); console.

How do you check if a date is before another date in Javascript?

To check if a date is before another date, compare the Date objects, e.g. date1 < date2 . If the comparison returns true , then the first date is before the second, otherwise the first date is equal to or comes after the second.

How do I get today's date in Javascript?

Use new Date() to generate a new Date object containing the current date and time. This will give you today's date in the format of mm/dd/yyyy. Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.


2 Answers

$('#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">
like image 121
Amadan Avatar answered Sep 26 '22 09:09

Amadan


var datep = $('#datepicker').val();  if(Date.parse(datep)-Date.parse(new Date())<0) {    // do something } 
like image 45
Srinivasan S Avatar answered Sep 24 '22 09:09

Srinivasan S