Ezilon.com - Target Your Audience, be Seen in Your Region

Javascript subtract times

You are viewing this site as a guest. Join our community to get your questions answered and share knowledge. Active members may advertise and ask for a website critique.

They have: 222 posts

Joined: Sep 1999

I'm modifying a timesheet application and have users enter times in hour:minutes format and select am/pm from a dropdown. I want to be able to subtract the ending time from the start time to get the # of hours worked on a project. It sounds like it'd be pretty simple, but I'm having a lot of trouble with it.

Here's my latest attempt.

function calculateHours()
{
var startTime = document.getElementById("<%=startTime.ClientID%>");
var endTime = document.getElementById("<%=endTime.ClientID%>");

if(startTime.value != '' && endTime.value != '')
{
var startPeriod = document.getElementById("<%=startPeriod.ClientID%>").value;
var endPeriod = document.getElementById("<%=endPeriod.ClientID%>").value;
var hoursOutput = document.getElementById("<%=Hours.ClientID%>");
startTime = startTime.value.split(":");
var startHour = parseInt(startTime[0]);
var startMinutes = parseInt(startTime[1]);
endTime = endTime.value.split(":");
var endHour = parseInt(endTime[0]);
var endMinutes = parseInt(endTime[1]);
var hours, minutes;

// Convert to 24 hour time to do calculation
if(startPeriod == "pm" && startHour != 12)
startHour += 12;
if(endPeriod == "pm" && endHour != 12)
endHour += 12;

var time1, time2, time3, today;
today = new Date();
time1 = new Date(today.getFullYear(), today.getMonth(), today.getDay(), startHour, startMinutes, 0);
time2 = new Date(today.getFullYear(), today.getMonth(), today.getDay(), endHour, endMinutes, 0);
time3 = new Date();
time3.setTime(time2.getTime() - time1.getTime());

//alert(startHour + " " + startMinutes + " " + endHour + " " + endMinutes + " " + time1.getTime() + " " + time2.getTime() + time3.getHours);
alert(time3.getTime);
}
}

'

Basically, it's converting both times to the # of milliseconds since the unix epoch and then subtracting them to get the difference, then setting that as the time on a 3rd object. But when I echo getTime it just shows the function decleration.

Abhishek Reddy's picture
Moderator

He has: 3,284 posts

Joined: Jul 2001

Your alert call should probably be [incode]alert(time3.getTime())[/incode]. As it is, [incode]time3.getTime[/incode] only refers to the function object, rather than calling it.