计算Javascript中的小时差异,但只能在一定时间内 [英] Calculating hour difference in Javascript, but only certain hours

查看:112
本文介绍了计算Javascript中的小时差异,但只能在一定时间内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定最好的方法来描述这个,但是我需要计算小时的差异(向下舍入),但只能在晚上8点到6点之间(或者在这种情况下是20点到06点)!

Unsure of the best way to describe this, but I need to calculate the difference in hours (rounded down) but only between 8pm and 6am (or rather 20:00 - 06:00 in this case!)

例如:

22:00 - 04:00 (6 hours)
02:40 - 10:20 (4 hours)
20:00 - 06:00 (10 hours)

不幸的是,我需要确切的日期,因为有些将跨越多天 - 只是为了增加混乱,我还需要排除某些日期完全为银行假期(我有一个数组的列表),但绝对不知道如何实现这一点 - 任何建议将是非常欢迎的,谢谢

Unfortunately I need to work on exact dates, because some will span over multiple days - and just to add to the confusion, I also need to exclude certain dates entirely for bank holidays (which I have a list of in an array) but have absolutely no idea how to implement this - any suggestions would be very welcome, thank you

推荐答案

只需关闭你样本中的输入内容:

Just going off what the inputs in your sample looks like:

// According to your example, your inputs are strings...
// t1 = "22:00"
// t2 = "04:00";

function hoursDiff(t1, t2){

   // Parse out the times, using radix 10 to
   // avoid octal edge cases ("08:00" & "09:00")
   var time1   = parseInt( t1, 10 );
   var time2   = parseInt( t2, 10 );
   var hours   = 0;

   while ( time1 !== time2 ){
      time1++;
      hours++;

      // If we've passed midnight, reset
      // to 01:00AM
      if ( time1 === 25 ){
         time1 = 1;
      }  
   }

   return hours;
}

这篇关于计算Javascript中的小时差异,但只能在一定时间内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆