I have a date object created from vars saved in a database.
var prevTime = Date(year,month,day,hour,minute);
I want to calculate the difference between this and the current time.
var thisTime = Date();
I am doing this:
prevTime.getTime() - thisTime.getTime();
It gives me a negative number that is very large. I divide by 1000 to get seconds and then divide by 3600 to get hours. I need an elapsed time in hours. I end up with a number that is like -756.00. If the current time is larger than the previous time, why is the number negative? What am I doing wrong?
Thanks,
Scott
In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.
Select a blank cell, enter this formula =IF(B2< A2, 1 + B2 - A2, B2- A2), A2 is start time, B2 is End time, and press Enter key then drag auto fill handle to fill formulas to the cells you want. 3. Click OK. The elapsed times have been displayed.
Definition of Elapsed Time Elapsed time is the amount of time that passes between the beginning and the end of an event. For example, Vernon ran a marathon in 2 hours and 15 minutes. He crossed the finish line at 10:30 a.m. What time did the race start?
The current time is larger than the previous time so subtracting a larger number from a smaller number gives you a negative number. Reverse the order if you want the positive difference in times. Is there more to the question than that?
Demonstration here: http://jsfiddle.net/jfriend00/NYSsp/
var prevTime = new Date(2011,1,1,0,0); // Feb 1, 2011
var thisTime = new Date(); // now
var diff = thisTime.getTime() - prevTime.getTime(); // now - Feb 1
alert(diff / (1000*60*60*24)); // positive number of days
First one must be smaller that you get negative. Your first date is in the past.
Here is an example:
var a = new Date(2011,7,5,2,1,1) - new Date(2011,7,5,1,1,1);
alert(a); // 3600000 which is millisecond for 1 hour. Divide by this to get hours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With