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
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.
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.
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.
$('#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">
var datep = $('#datepicker').val(); if(Date.parse(datep)-Date.parse(new Date())<0) { // do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With