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

时间:2014-11-01 21:02:07

标签: javascript momentjs

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

Javascript示例:

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

我无法访问实际的Date对象,这就是为什么这稍微难一些。 然而,我正在使用moment.js,所以如果你有关于如何使用它的建议 情况,这将是完美的。

2 个答案:

答案 0 :(得分:1)

这对于一些基本的除法和减法来说是非常微不足道的:

// 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

答案 1 :(得分:0)

这只是一个数学问题......

看起来像这样:

&#13;
&#13;
var now = 2230;
var then = 529;

function calculateMinutesDifference(now, then){
  var nowMinutes = getMinutes(now);
  var thenMinutes = getMinutes(then);
  return thenMinutes >= nowMinutes
         ? thenMinutes - nowMinutes
         : (thenMinutes+60) - nowMinutes;
}


function calculateHoursDifference(now, then){
  var nowHours = getHours(now);
  var thenHours = getHours(then);
  return then >= now
  ? thenHours - nowHours
  : (thenHours+(calculateMinutesDifference(now,then) == 0 ? 24 : 23)) - nowHours;
}

function getMinutes(time){
  return time % 100;
}

function getHours(time){
  return (time - getMinutes(time))/100;  
}

alert("minutes difference: " + calculateMinutesDifference(now, then));
alert("hours difference: " + calculateHoursDifference(now, then));
&#13;
&#13;
&#13;

记住,当你有小时&lt;时,不要使用前导0 10,因为javascript会认为它不是十进制数。