Difference Between two dates in Javascript


Hello.

Some times we came around a problem where we needed to know the difference between 2 dates in javascript. Also, in some cases we need to validate a date against another date. In these cases we search in the internet for a suitable function which takes 2 dates as arguments and finally let us know the difference between those.

Here, I have found so many scripts, but some of which are not working and some I do not understand and some does not provide us a simple result as we want. So, I have taken reference of those scripts and marged them into a suitable one to produce a new script which is giving us output as I wanted it to do.

Here it is:

First, we need a html form and 2 input type text fileds to enter 2 dates. Here some may wanted to add the time also.

<form onSubmit=”return checkDate(this);”>
<table>
 <tr>
  <td>
   <pre>
   First Date:<input type=”text” name=”firstdate” value=”” size=10 maxlength=10> (MM/DD/YYYY format)<br/>
   Time: <input type=”text” name=”firsttime” value=”” size=10 maxlength=10> (HH:MM:SS format)<br/>
   
   Second Date: Date: <input type=”text” name=”seconddate” value=”” size=10 maxlength=10> (MM/DD/YYYY format)<br/>
   Time: <input type=”text” name=”secondtime” value=”” size=10 maxlength=10> (HH:MM:SS format)<br/>
   
   <center><input type=”submit” value=”Get Difference!”></center>
   </pre>
  </td>
 </tr>
</table>
</form>

So, this form has 2 text fileds for dates and 2 other for times, and a button to get the difference.

This form takes date in “MM/DD/YYYY” format and time in “HH:MM:SS” format.

We can add a function to validate these dates or we can simply specify the date text fileds as readonly and add a suitable javascript calendar to input correct dates. (Like I have used in : http://www.hotelsagorika.com/reservation.html)

Now after clicking the submit button we need to add suitable code to check the dates:

So, we will put this script into the HEAD section of the HTML.

<script type=”text/javascript”>

function isValidDate(dateStr) {
 // Date validation Function 
 // Checks For the following valid Date formats:
 // MM/DD/YY MM/DD/YYYY MM-DD-YY MM-DD-YYYY
 
 var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit Year
 
 var matchArray = dateStr.match(datePat); // Is the format ok?
 if (matchArray == Null) {
  alert(dateStr + ” Date is not in a valid format.”)
  return false;
 }
 
 Month = matchArray[1]; // parse Date into variables
 Day = matchArray[3];
 Year = matchArray[4];
 
 if (Month < 1 || Month > 12) { // check Month range
  alert(“Month must be between 1 and 12.”);
  return false;
 }
 
 if (Day < 1 || Day > 31) {
  alert(“Day must be between 1 and 31.”);
  return false;
 }
 
 if ((Month==4 || Month==6 || Month==9 || Month==11) && Day==31) {
  alert(“Month “+Month+” doesn’t have 31 days!”)
  return false;
 }
 
 if (Month == 2) { // check For february 29th
  var isleap = (Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0));
  if (Day>29 || (Day==29 && !isleap)) {
   alert(“February ” + Year + ” doesn’t have ” + Day + ” days!”);
   return false;
  }
 }
 return true;
}

function isValidTime(timeStr) {
 // Checks if time Is In HH:MM:SS AM/PM format.
 // The seconds And AM/PM are optional.
 
 var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
 
 var matchArray = timeStr.match(timePat);
 if (matchArray == Null) {
  alert(“Time is not in a valid format.”);
  return false;
 }
 
 Hour = matchArray[1];
 Minute = matchArray[2];
 Second = matchArray[4];
 ampm = matchArray[6];
 
 if (Second==””) { Second = null; }
 if (ampm==””) { ampm = Null }
 
 if (Hour < 0 || Hour > 23) {
  alert(“Hour must be between 1 and 12. (or 0 and 23 for military time)”);
  return false;
 }
 if (Hour <= 12 && ampm == Null) {
  if (confirm(“Please indicate which time format you are using. OK = Standard Time, CANCEL = Military Time”)) {
   alert(“You must specify AM or PM.”);
   return false;
  }
 }
 if (Hour > 12 && ampm != Null) {
  alert(“You can’t specify AM or PM for military time.”);
  return false;
 }
 if (Minute < 0 || Minute > 59) {
  alert (“Minute must be between 0 and 59.”);
  return false;
 }
 if (Second != Null && (Second < 0 || Second > 59)) {
  alert (“Second must be between 0 and 59.”);
  return false;
 }
 return true;
}

function checkDate(dateform) {
 date1 = new Date();
 date2 = new Date();
 diff = new Date();
 
 if (isValidDate(dateform.firstdate.value) && isValidTime(dateform.firsttime.value)) { // Validates first Date
  date1temp = new Date(dateform.firstdate.value + ” ” + dateform.firsttime.value);
  date1.setTime(date1temp.getTime());
 }
 else return false; // otherwise exits
 
 if (isValidDate(dateform.seconddate.value) && isValidTime(dateform.secondtime.value)) { // Validates Second Date
  date2temp = new Date(dateform.seconddate.value + ” ” + dateform.secondtime.value);
  date2.setTime(date2temp.getTime());
 }
 else return false; // otherwise exits
 
 // sets difference Date To difference of first Date And Second Date
 
 diff.setTime(Math.abs(date1.getTime() – date2.getTime()));
 
 timediff = diff.getTime();
 
 weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
 timediff -= weeks * (1000 * 60 * 60 * 24 * 7);
 
 days = Math.floor(timediff / (1000 * 60 * 60 * 24));
 timediff -= days * (1000 * 60 * 60 * 24);
 
 hours = Math.floor(timediff / (1000 * 60 * 60));
 timediff -= hours * (1000 * 60 * 60);
 
 mins = Math.floor(timediff / (1000 * 60));
 timediff -= mins * (1000 * 60);
 
 secs = Math.floor(timediff / 1000);
 timediff -= secs * 1000;
 
 alert(“Difference = ” + weeks + ” weeks, ” + days + ” days, ” + hours + ” hours, ” + mins + ” minutes, and ” + secs + ” seconds”);

 return false; // form should never submit, returns False
}

</script>

If you have specified the text fileds as read only and added a calendar, then you do not need the validattion methods, then the script will look like:

<script type=”text/javascript”>

function checkDate(dateform) {
 date1 = new Date();
 date2 = new Date();
 diff = new Date();
 
 date1temp = new Date(dateform.firstdate.value + ” ” + dateform.firsttime.value);

//If you do not need the time then you can replace the above line with this
// date1temp = new Date(dateform.firstdate.value + ” 00:00:00″);

 date1.setTime(date1temp.getTime());
  
 date2temp = new Date(dateform.seconddate.value + ” ” + dateform.secondtime.value);

//If you do not need the time then you can replace the above line with this
// date2temp = new Date(dateform.seconddate.value + ” 00:00:00″);

 date2.setTime(date2temp.getTime());
 
 // sets difference Date To difference of first Date And Second Date
 
 diff.setTime(Math.abs(date1.getTime() – date2.getTime()));
 
 timediff = diff.getTime();
 
 weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
 timediff -= weeks * (1000 * 60 * 60 * 24 * 7);
 
 days = Math.floor(timediff / (1000 * 60 * 60 * 24));
 timediff -= days * (1000 * 60 * 60 * 24);
 
 hours = Math.floor(timediff / (1000 * 60 * 60));
 timediff -= hours * (1000 * 60 * 60);
 
 mins = Math.floor(timediff / (1000 * 60));
 timediff -= mins * (1000 * 60);
 
 secs = Math.floor(timediff / 1000);
 timediff -= secs * 1000;
 
 alert(“Difference = ” + weeks + ” weeks, ” + days + ” days, ” + hours + ” hours, ” + mins + ” minutes, and ” + secs + ” seconds”);

 return false; // form should never submit, returns False
}

</script>

Now, suppose we want to know if the second date is after the first date or vice versa, i.e. if the first date is 30 th October, 2008 and seconda date is 02 nd November, 2008 then it will accept the dates otherwise, like if the 1st date is 28 th October 2008 and the second is 25th October 2008, it will not accept.

So, wee need to modify the above function slightly:

function checkDate(dateform) {
 date1 = new Date();
 date2 = new Date();
 diff = new Date();
 
 if (isValidDate(dateform.firstdate.value) && isValidTime(dateform.firsttime.value)) { // Validates first Date
  date1temp = new Date(dateform.firstdate.value + ” ” + dateform.firsttime.value);
  date1.setTime(date1temp.getTime());
 }
 else return false; // otherwise exits
 
 if (isValidDate(dateform.seconddate.value) && isValidTime(dateform.secondtime.value)) { // Validates Second Date
  date2temp = new Date(dateform.seconddate.value + ” ” + dateform.secondtime.value);
  date2.setTime(date2temp.getTime());
 }
 else return false; // otherwise exits
 
 // sets difference Date To difference of first Date And Second Date
 
 var dif = date2-date1;
 
 if(dif >=0){ // 2nd date is after the 1st date
  return true;
 }else{
  return false;
 }

}

Hope this article will help you understanding the date related issues better.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s