问题描述
我有两个< input type = time>
。默认情况下,每个输入都将时间值作为字符串收集。例如, 08:30
。
I have two <input type="time">
. By default, each input collects a time value as a string. For example, "08:30"
.
如何将该字符串转换为对象,然后该对象将启用计算?
How can I convert this string into an object which would then enable computation? Is it possible to avoid involving the use of date
in this approach?
最后,我想避免在这种方法中使用 date
吗?计算两个时间
字符串之间的差,然后以 minutes 返回结果。例如,预期的返回值 08:00
和 09:00
将为 60
分钟。
In the end, I would like to compute the difference between two time
strings and then return the result in minutes. For example, the expected return value of08:00
and 09:00
would be 60
minutes.
推荐答案
就像只用纸和笔一样做:
Just do it as if you only had pen and paper:
- 12:45 => 12× 60 + 45 = 765分钟
- 08:30 => 8× 60 + 30 = 510分钟
- 765-510 = 255
- 整数除法:255/60 = 4小时
- 剩余:255-60× 4 = 15分钟
- 结果:04:15
- 12:45 => 12 × 60 + 45 = 765 minutes
- 08:30 => 8 × 60 + 30 = 510 minutes
- 765 - 510 = 255
- Integer division: 255 / 60 = 4 hours
- Remainer: 255 - 60 × 4 = 15 minutes
- Result: 04:15
您可以使用常规从字符串中进行解析表达式:
You can parse from string using regular expressions:
var parts = "08:45".match(/^(\d+):(\d+)$/);
console.log(+parts[1], +parts[2], +parts[1] * 60 + +parts[2]);
...并且格式化为字符串也不是很困难。
... and formatting back to string should not be very difficult either.
这篇关于Javascript:在不涉及日期的情况下找到两个“时间”字符串之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!