So I'm just learning Javascript and I'm trying to create a calculator that can subtract time. I have the other parts working (although I'd love feedback on my code there as I'm sure it can be majorly improved on), I just need to get the time subtracting right. I'm doing simple math so when I subtract 1:30 (hours and minutes are separate values) from 2:00 it gives me 1:30 instead of just 00:30.
Another problem is the gold per hour doesn't calculate unless I hit the 'Get Results' button twice....
This is the first script I have ever written so please let me know what I should be doing, I want to do this the best and easiest way possible.
Calculator and script are here:
http://www.coolestwebsiteintheuniverse.com/gold-calculator/
http://www.coolestwebsiteintheuniverse.com/gold-calculator/calc.js
I'd also like the ability to expand it to 10 rows and average all of them but I think I could figure that out on my own once this part is figured out.
Thanks
Have you tried using date function to subtract.??
var T1=new Date("September 5, 2012 8:10:00");
var T2=new Date("September 5, 2012 13:35:00");
var diff=new Date();
diff.setTime(T2-T1);
alert(diff.getHours()+":"+diff.getMinutes())
The problem is that you're treating the hours separate from the minutes in making time calculations. You need to combine them with something like this (untested):
var starthh = // ...
var startmm = // ...
var endhh = // ...
var endmm = // ...
var elapsedMinutes = (60 * endhh + endmm) - (60 * starthh + startmm)
var displayTime = Math.floor(elapsedMinutes / 60) + ":"
+ ("00" + (elapsedMinutes % 60)).slice(-2)
That last bit, ("00" + (elapsedMinutes % 60)).slice(-2)
takes the minutes modulo 60, appends it to the string "00" and then takes the last two charactes, as a quick way to zero pad single-digit numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.