Solved

# Help with Date Difference displayed in hours

Posted on 2008-11-14
Medium Priority
906 Views
I have two fields, startDate and endDate that are datetime fields in a .NET page.  I would like to have JavaScript do the math for me, but I can't seem to get the value that I need, I am at the low end of the intermediate level with JS so be kind!

I need the result displayed in hours and tenths (eg. 0.2 or 115577.9, etc). The kicker for me is that I need to calculate 8 hours for each 24 hour period (including weekends, holidays, etc).

I found the following on the JavaScript Source website but after many hours of attempted manipulation, I feel dumber now than when I started.  :(

Any help is greatly appreciated.
chuck
``````<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Original:  Ronnie T. Moore -->
<!-- Web Site:  The JavaScript Source -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
function isValidDate(dateStr) {
// Date validation function courtesty of
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

// 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) {
// Time validation function courtesty of
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

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

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

return false; // form should never submit, returns false
}
//  End -->
</script>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<center>
<form onSubmit="return dateDiff(this);">
<table>
<tr><td>
<pre>
First Date:   Date: <input type=text name=firstdate value="" size=10 maxlength=10>  (MM/DD/YYYY format)
Time: <input type=text name=firsttime value="" size=10 maxlength=10>  (HH:MM:SS format)

Second Date:  Date: <input type=text name=seconddate value="" size=10 maxlength=10>  (MM/DD/YYYY format)
Time: <input type=text name=secondtime value="" size=10 maxlength=10>  (HH:MM:SS format)

<center><input type=submit value="Calculate Difference!">

Date Difference:<br>
<input type=text name=difference value="" size=60>
</center>
</pre>
</td></tr>
</table>
</form>
</center>

<p><center>
<font face="arial, helvetica" size="-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>
``````
0
Question by:cwickens
• 2

LVL 41

Accepted Solution

HonorGod earned 2000 total points
ID: 22960085
Something like this perhaps?
``````<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<title>Time Delta</title>

<script type='text/javascript'>
<!-- Original:  Ronnie T. Moore                             -->
<!-- Web Site:  The JavaScript Source                       -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin
function isValidDate( dateStr ) {
// Date validation function courtesty of
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

// 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 ) {
// Time validation function courtesty of
// Sandeep V. Tamhankar (stamhankar@hotmail.com) -->

// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

function d2( val ) {
return ( val < 10 ) ? '0' + val : val;
}

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 ];
if ( matchArray[ 4 ] ) {
second = matchArray[ 4 ]
} else {
second = 0
}

if ( matchArray[ 5 ] ) {
ampm = matchArray[ 5 ];
} else {
ampm = null
}
//  alert( 'time: "' + hour + '" "' + minute + '" "' + second + '" "' + ampm + '"' )

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;
}
timeVal = d2( hour ) + ':' + d2( minute )
//  alert( 'timeVal: ' + timeVal )

if ( second && ( second < 0 || second > 59 ) ) {
alert( "Second must be between 0 and 59." );
return false;
} else
timeVal += ':' + d2( second )
//  alert( 'timeVal: ' + timeVal )

if ( ampm && ( hour < 13 ) ) {
timeVal += ' AM'
} else if ( ampm ) {
timeVal += ' PM'
}
//  alert( 'timeVal: ' + timeVal )

return true;
}

function dateDiff( 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 );
date1temp = new Date( dateform.firstdate.value + " " + timeVal );
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 );
date2temp = new Date( dateform.seconddate.value + " " + timeVal );
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() ) );
//  alert( 'date1: ' + date1 + '\ndate2: ' + date2 + '\ndiff: ' + diff )

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";
dateform.difference.value =  hours.toFixed( 2 )

return false; // form should never submit, returns false
}
//  End -->
</script>

<body>

<center>
<form onSubmit="return dateDiff(this);">
<table>
<tr><td>
<pre>
First Date:   Date: <input type=text name=firstdate value="" size=10 maxlength=10>  (MM/DD/YYYY format)
Time: <input type=text name=firsttime value="" size=10 maxlength=10>  (HH:MM:SS format)

Second Date:  Date: <input type=text name=seconddate value="" size=10 maxlength=10>  (MM/DD/YYYY format)
Time: <input type=text name=secondtime value="" size=10 maxlength=10>  (HH:MM:SS format)

<center><input type=submit value="Calculate Difference!">

Date Difference:<br>
<input type=text name=difference value="" size=60>
</center>
</pre>
</td></tr>
</table>
</form>
</center>

</body>
</html>
``````
0

LVL 41

Expert Comment

ID: 23546878
Thanks for the grade & points.  Good luck & have a great day
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
###### Suggested Courses
Course of the Month14 days, 15 hours left to enroll