Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 284
JonoB Avatar asked Nov 21 '11 17:11

JonoB


People also ask

How do you check if input is a date?

One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.

Does new Date () Return current date?

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.


1 Answers

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.

like image 138
James Hill Avatar answered Sep 16 '22 20:09

James Hill