简体   繁体   English

简单的JavaScript时间/每小时金钱计算器

[英]Simple javascript time/money per hour calculator

So I'm just learning Javascript and I'm trying to create a calculator that can subtract time. 因此,我只是在学习Javascript,并且试图创建一个可以减少时间的计算器。 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. 我正在做简单的数学运算,所以当我从2:00减去1:30(小时和分钟是单独的值)时,它得到的是1:30,而不仅仅是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/

http://www.coolestwebsiteintheuniverse.com/gold-calculator/calc.js 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. 我还希望能够将其扩展到10行并将它们平均化,但是我认为一旦弄清了这一部分,我就可以自行解决。

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. 最后一个位("00" + (elapsedMinutes % 60)).slice(-2)将分钟取模60,将其附加到字符串” 00“,然后采用最后两个字符,作为将零填充的快速方法一位数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM