How to check if input date is equal to today's date?

I have a form input with an id of 'date_trans'. The format for that date input (which is validated server side) can be any of:

  • dd/mm/yyyy
  • dd-mm-yyyy
  • yyyy-mm-dd
  • yyyy/mm/dd

However, before posting the form, I'd like to check if the date_trans field has a date that is equal to today's date. Its ok if the date taken is the client's date (i.e. it uses js), since I run a double check on the server as well.

I'm totally lost on how to do the date comparrison in jQuery or just plain old javascript. If it helps, I am using the jquery datepicker


Solution 1:

A simple date comparison in pure JS should be sufficient:

// Create date from input value
var inputDate = new Date("11/21/2011");

// Get today's date
var todaysDate = new Date();

// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
    // Date equals today's date
}

Here's a working JSFiddle.

Solution 2:

for completeness, taken from this solution:

You could use toDateString:

var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());

no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho