gpt4 book ai didi

javascript - 如何计算 Javascript 中两个 'HHmm' 之间的小时数?

转载 作者:行者123 更新时间:2023-12-03 11:32:05 24 4
gpt4 key购买 nike

是否可以计算两个“HHmm”字符串之间的分钟数或小时数。

Javascript 示例:

var now = 2050,
next = 0850,
minutesUntilNext = *now until then code*,
hoursUntilNext = *minutes to hours code*;

我无权访问实际的 Date 对象,这就是为什么这有点困难。不过,我正在使用 moment.js,所以如果您对如何在此使用它有建议这样的话就完美了。

最佳答案

这对于一些基本的除法和减法来说非常简单:

// http://stackoverflow.com/a/10075654/560648
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

/**
* Given two times in HHMM format, returns the timespan between them
* in HH:MM format.
*
* %next is assumed to come later than %now, even if its absolute value
* is lower (so, the next day).
*/
function compareTimes(now, next) {

// Perform hours validation before we potentially add 24 hours (see below)
if (now >= 2400 || next >= 2400)
throw "Hours out of bounds";

// If next is "earlier" than now, it's supposed to be tomorrow;
// adding 24 hours handles that immediately
if (next < now) next += 2400;

// Split inputs into hours and minutes components
now = [parseInt(now / 100, 10), now % 100];
next = [parseInt(next / 100, 10), next % 100];

// Finally, validate the minutes
if (now[1] >= 60 || next[1] >= 60)
throw "Minutes out of bounds";

// Perform the comparisons
var minutesUntilNext = next[1] - now[1];
var hoursUntilNext = next[0] - now[0];

// And return the result
return padDigits(hoursUntilNext, 2) + ':' + padDigits(minutesUntilNext, 2);
}

console.log(doThisThing(2050, 0850)); // 12:00
console.log(doThisThing(2300, 0145)); // 02:45
//console.log(doThisThing(2500, 0000)); // error
//console.log(doThisThing(2460, 0000)); // error

关于javascript - 如何计算 Javascript 中两个 'HHmm' 之间的小时数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com