最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

date - Calculating hour difference in Javascript, but only certain hours - Stack Overflow

programmeradmin1浏览0评论

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!)

For example:

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 wele, thank you

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!)

For example:

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 wele, thank you

Share Improve this question edited Aug 17, 2012 at 12:27 S.L. Barth is on codidact. 8,25371 gold badges53 silver badges67 bronze badges asked Apr 27, 2012 at 15:03 NickNick 3,97521 gold badges60 silver badges76 bronze badges 2
  • Can we see a sample of your input data? Are you working with plete dates, or just times? – Daniel Szabo Commented Apr 27, 2012 at 15:37
  • why is the difference (10 hours) in your third example, it must be (2 hours) as your second example. – Okan Kocyigit Commented Apr 27, 2012 at 15:49
Add a ment  | 

2 Answers 2

Reset to default 5

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;
}

Ok, this was a nice puzzle. It really cost me too much time but it was fun.

Full working code below (jsfiddle here):

function isHoliday(/*Date*/ date) {
    for(var i = 0; i < holidays.length; i++) {
        if(holidays[i].getTime() == date.getTime()) {
            return true;
        }
    }
    return false;
}

function diffHours(/*Date*/ d1, /*Date*/ d2) {
    var date1 = new Date(d1.getUTCFullYear()+"-"+(d1.getUTCMonth()+1)+"-"+d1.getUTCDate()+" UTC");
    var date2 = new Date(d2.getUTCFullYear()+"-"+(d2.getUTCMonth()+1)+"-"+d2.getUTCDate()+" UTC");

    var sum = 0;
    var oneday = 24*3600*1000;
    var hours, date;

    // first day
    if(!isHoliday(date1)) {
        // decrease by a whole day first (will be added later)
        sum -= 10;

        // add real hours
        hours = d1.getUTCHours() + d1.getUTCMinutes() / 60;
        if(hours <= 6) {
            sum += 10 - hours;
        } else if(hours <= 20) {
            sum += 4;
        } else {
            sum += 24 - hours;
        }
    }

    // last day
    if(!isHoliday(date2)) {
        // decrease by a whole day first (will be added later)
        sum -= 10;

        // add real hours
        hours = d2.getUTCHours() + d2.getUTCMinutes() / 60;
        if(hours <= 6) {
            sum += hours;
        } else if(hours <= 20) {
            sum += 6;
        } else {
            sum += hours - 14;
        }
    }

    // whole days
    while(date1 <= date2) {
        if(!isHoliday(date1)) {
            sum += 10;
        }

        // increase date by 1 day
        date1.setTime(date1.getTime() + oneday);
    }

    return Math.floor(sum);
}

// ==============
// examples below
// --------------

// array of Dates (in UTC) to skip
var holidays = [
    new Date("2012-01-04 UTC"),
];

for(var i = 0; i < holidays.length; i++) {
    console.log('holiday: ', holidays[i].toUTCString());
}

a = new Date("2012-01-01 12:00 UTC");
b = new Date("2012-01-02 12:00 UTC");
c = new Date("2012-01-02 22:00 UTC");
d = new Date("2012-01-03 07:00 UTC");
e = new Date("2012-01-05 12:00 UTC");

console.log({d1: a.toUTCString(), d2: b.toUTCString(), hours: diffHours(a, b)});
console.log({d1: b.toUTCString(), d2: c.toUTCString(), hours: diffHours(b, c)});
console.log({d1: c.toUTCString(), d2: d.toUTCString(), hours: diffHours(c, d)});
console.log({d1: d.toUTCString(), d2: e.toUTCString(), hours: diffHours(d, e)});
发布评论

评论列表(0)

  1. 暂无评论