Javascript subtract times
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 posted this at 18:48 — 17th April 2007.
He has: 3,348 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.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.