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.

Useful and Cool and easy to manage Javascript Calendar


Hi,
Many of you often come around a problem where you need a Javascript Calendar or Datepicker. You can get a lot from searching in Google. But the problem is that they are not easy to configure.

But I have came around a script in DHTML Goodies (JS Calendar) which is brilliant. You can download the code from DHTML Goodies.

First put these two lines befoer </head> section.
As you can understand one of this is a CSS (Styel Sheet) File and another one is a Javascript file (which is the main Javascript file holding the functions of Calendar).

<link type=”text/css” rel=”stylesheet” href=”dhtmlgoodies_calendar/dhtmlgoodies_calendar.css?random=20051112″ mce_href=”dhtmlgoodies_calendar/dhtmlgoodies_calendar.css?random=20051112″ media=”screen”></LINK>
 <SCRIPT type=”text/javascript” src=”dhtmlgoodies_calendar/dhtmlgoodies_calendar.js?random=20060118″ mce_src=”dhtmlgoodies_calendar/dhtmlgoodies_calendar.js?random=20060118″></script>

Note that the two files  dhtmlgoodies_calendar.js and dhtmlgoodies_calendar.css are located in dhtmlgoodies_calendar directory of your server or you can you any other directory also.

Now create a Form element in <body> tag and you can put the below lines. 

<form>
<p>Click on the “Cal” buttons to see how the calendar works</p>
<table>
 <tr><td colspan=”3″><b>Dates only</b></td></tr>
 <tr>
<td>Date input 1(YYYY/MM/DD): </td><td><td>
<input type=”text” value=”2004/02/02″ name=”theDate”>
<input type=”button” value=”Cal” onclick=”displayCalendar(document.forms[0].theDate,’yyyy/mm/dd’,this)”>
</td>
</tr>
 </table>
</form>

Here you can easily understand that document.forms[0].theDate is the text box element where you want the selected dates to be inserted.
forms[0] refers to the first form in the document element or the body tag. Here is only one form. You can access the form by name or getElementById also.

Suppose the form name is dateForm: <form name=”dateForm” >
then the you can access this the text box by document.dateForm.theDate.
If you use a id attribute in form element : <form name=”dateForm” id=”dateForm”>
then you can access the text box by document.getElementById(“dateForm”).theDate.

Or you can access the text box directly by giving a id attribute to the text box element
<input type=”text” value=”2004/02/02″ name=”theDate” id=”theDate”>
Then you can access it by document.getElementById(“theDate”) only . 🙂

So you can understand that clicking on the Button whose Value is Cal you invoke the onclick() event of the input type. And it calls the function displayCalendar with parameters
1. the inout type where the text is be put.
2. the date format. You can specify a lot of formats here.

Link to download this script.