User Id :    Password :      New Member   Forgot Password  
 
Find Date Difference using Java Script
Description Enter two dates (including the time!) and this script will display the number of weeks, days, hours, minutes, and seconds between the two. The second’s field is optional, too. For an example, try entering your birthdates and compare it to today.   No. of Views     2044
  Rating     0
Author Najmul Hoda   Posted On     21 Jan 2010
Tags Java Script    

Sample Code   Download Code

Introduction

Before explaining the article, I would like to thank all readers who read my article and voted for it. Your appreciation for my article gives me strength to write more good articles. Hope in future I will get your valuable comments and suggestions. Now I won't waste your time and come back to the topic. I have written this article on ‘Find Date Difference using Java Script’. In this article, Enter two dates (including the time!) and this script will display the number of weeks, days, hours, minutes, and seconds between the two. The second’s field is optional, too. For an example, try entering your birthdates and compare it to today.

Using Code 

Using this JavaScript, You can find the date difference.

We will cover this article in the following sections:

  1. Design of the page.
  2. Function to check the valid date format.
  3. Function to check the valid time format. 
  4. Function to get the Date Difference. 

Now let's get started with step 1.

1. Design of the page

I have used a default.aspx page to show the design on that page.

<table>

<tr><td style="height: 100%; width: 30%;">

<pre>

    <span style="font-family: Verdana">

    <table id="TABLE1" border="1" style="width: 70%; height: 100%">

    <tr>

    <td style="width: 40%" align="left">First Date:</td>

    <td style="width: 60%" align="left"><input type="text" name="firstdate" value="" size="10" maxlength="10" id="Text1" style="font-family: Verdana"/>(MM/DD/YYYY format)</td>

    </tr>

    <tr>

    <td style="width: 40%" align="left">Time:</td>

    <td style="width: 60%" align="left"><input type="text" name="firsttime" value="" size="10" maxlength="10" style="font-family: Verdana"/>(HH:MM:SS format) </td>

    </tr>

    <tr>

    <td style="width: 40%" align="left">Second Date:</td>

    <td style="width: 60%" align="left"><input type="text" name="seconddate" value="" size="10" maxlength="10" style="font-family: Verdana"/>(MM/DD/YYYY format)</td>

    </tr>

    <tr>

    <td style="width: 40%" align="left">Time: </td>

    <td style="width: 60%" align="left"><input type="text" name="secondtime" value="" size="10" maxlength="10" style="font-family: Verdana"/>(HH:MM:SS format)</td>

    </tr>

    <tr>

    <td colspan="2" align="center" ><input type="submit" value="Calculate Difference!" style="font-family: Verdana"/></td>

    </tr>

    <tr>

    <td colspan="2" align="center">Date Difference:<input type="text" name="difference" value="" style="width: 100%"/> </td>

    </tr>

    </table>

     </span><span style="font-family: Verdana"></span><span style="font-family: Verdana"></span>

   

</pre>

</td></tr>

</table>

2. Function to check the valid date format

 

Function isValidDate() is used to check the date format. Whether format is like  MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY or not.

 

function isValidDate(dateStr)

{

 

//requires 4 digit year

 

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

 

// is the format ok?

var matchArray = dateStr.match(datePat);

 

if (matchArray == null)

{

alert(dateStr + " Date is not in a valid format.")

return false;

}

// parse date into variables

month = matchArray[1];

day = matchArray[3];

year = matchArray[4];

 

// check month range

if (month < 1 || month > 12)

{

alert("Month must be between 1 and 12.");

return false;

}

// check days range

 

if (day < 1 || day > 31)

{

alert("Day must be between 1 and 31.");

return false;

}

// check months days range

 

if ((month==4 || month==6 || month==9 || month==11) && day==31)

{

alert("Month "+month+" doesn't have 31 days!")

return false;

}

 

// check for february 29th

if (month == 2)

{

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;

}

3. Function to check the valid time format

Function isValidTime() is used to check the Time format. Check if time is in HH:MM:SS AM/PM format.

function isValidTime(timeStr)

{

 

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;

}

4. Function to get the Date Difference

Function dateDiff() is used to get the date difference.

function dateDiff(dateform)

{

date1 = new Date();

date2 = new Date();

diff  = new Date();

 

// Validates first date

if (isValidDate(dateform.firstdate.value) && isValidTime(dateform.firsttime.value))

{

date1temp = new Date(dateform.firstdate.value + " " + dateform.firsttime.value);

date1.setTime(date1temp.getTime());

}

 

// otherwise exits

else return false;

 

// Validates second date

if (isValidDate(dateform.seconddate.value) && isValidTime(dateform.secondtime.value))

{

date2temp = new Date(dateform.seconddate.value + " " + dateform.secondtime.value);

date2.setTime(date2temp.getTime());

}

// otherwise exits

else return false;

 

// 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;

 

dateform.difference.value = weeks + " weeks, " + days + " days, " + hours + " hours, " + mins + " minutes, and " + secs + " seconds";

 

// form should never submit, returns false

return false;

}

 

When user click on the button on the submittion of form a function dateDiff() will call.Which will write with the form tag like below 

<form onsubmit="return dateDiff(this);">
</
form>

dateDiff() function will call the function isValidDate () to verify the date format. And call isValidTime()to verify the time format. If the date format and the time format is correct then user can see the difference in the form of weeks,days,hours,mins and seconds.

 

About Author

About Author He is a team lead, having 8+ years of experience. He loves writing technical article for .Net developers. Najmul Hoda
No Photo
 
Country United States
Company BirlaSoft
Home Page http://www.magixchat.com

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code