时间计算算法

时间:2016-10-10 14:33:26

标签: javascript time

我需要时间计算算法的帮助。这不是一个通常的时间操作,所以momentjs在这里无济于事。

简而言之,我有一个时间量,我想减少另一个时间量,例如:

 120:30 // total time
-  1:30 // time 2
 119:00 // result

总时间是我的应用中使用的任务的估计时间,因此它不是基于24小时的时间。 时间2 是工作时间的结果,就像我在这项任务上工作2次一样,先是30分钟,然后是60分钟,所以一个半小时。

在我的算法中,我可以将总工作时间总计为分钟,但我无法从总时间本身实施减少计算。

这是我的代码注释部分:

// Types = 1- Start, 2- Stop

var estimatedTime = "120:30", // One hundred twenty hours and thirty minutes
    timeHistory = [{
      type: 1,
      time: new Date(2016, 9, 10, 1, 0, 0) // Start action
    }, {
      type: 2,
      time: new Date(2016, 9, 10, 1, 30, 0) // Adds 30 minutes since last history
    },  {
      type: 1,
      time: new Date(2016, 9, 10, 1, 40, 0) // Start again after 10 minutes interval
    },  {
      type: 2,
      time: new Date(2016, 9, 10, 2, 40, 0) // Adds 60 minutes since last history
    }];
   
// Total of 90 minutes of work

//----------------------------------
// Calculation algorithm

var totalTime = 0,
    lastTime = null;

timeHistory.forEach(function(h) {
  // Sums to totalTime the diff between last "Start" and the current "Stop" time
  if (lastTime && h.type != 1) {
    totalTime+= h.time.getTime() - lastTime.getTime();
  }

  lastTime = h.time;
});

// If time is running (type 1 = Start), sums the current time
if (timeHistory[timeHistory.length - 1].type == 1) {
  totalTime+= (new Date()).getTime() - lastTime.getTime();
}

var t1 = Math.floor(totalTime / 60000); // Get total minutes
console.log(t1); // So far so good
    
var estTime = estimatedTime.split(":").map(Number), // Getting time hours and minutes as numbers
    resultMinutes = 60 - (t1 % estTime[1]),
    resultHours = (Math.floor(t1 / estTime[1]) > 0 ? (estTime[0] - Math.floor(t1 / estTime[1])) : 0);
    
if (resultMinutes == 60) {
  resultHours+= 1;
  resultMinutes = 0;
}
    
console.log("Result:", resultHours + ":" + resultMinutes);

Fiddle version

正如你所看到的,直到“到目前为止这么好”(第41行),一切似乎都运转正常。我的问题是在那之后的计算。这是一团糟,我可以发展它。代码段案例中的结果应为119:00。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

这可以更简单地完成,但因为它是您的代码,而且学习起来很重要,我只需编辑并添加更多带注释的行。希望这会对你有所帮助。



    // Types = 1- Start, 2- Stop

    var estimatedTime = "120:30", // One hundred twenty hours and thirty minutes
        timeHistory = [{
          type: 1,
          time: new Date(2016, 9, 10, 1, 0, 0) // Start action
        }, {
          type: 2,
          time: new Date(2016, 9, 10, 1, 30, 0) // Adds 30 minutes since last history
        },  {
          type: 1,
          time: new Date(2016, 9, 10, 1, 40, 0) // Start again after 10 minutes interval
        },  {
          type: 2,
          time: new Date(2016, 9, 10, 2, 40, 0) // Adds 60 minutes since last history
        }];
       
    // Total of 90 minutes of work

    //----------------------------------
    // Calculation algorithm

    var totalTime = 0,
        lastTime = null;

    timeHistory.forEach(function(h) {
      // Sums to totalTime the diff between last "Start" and the current "Stop" time
      
 if (lastTime && h.type != 1) {
        totalTime+= h.time.getTime() - lastTime.getTime();
      }


      lastTime = h.time;
    });

totalTimeInMins = totalTime/(1000*60); // Get total minutes of work done

console.log(totalTimeInMins + " mins of work" );

var estTime = estimatedTime.split(":").map(Number); // Getting time hours and minutes as numbers

var estTimeInMins = estTime[0]*60+estTime[1] ;//converting esitmated time to minutes
 var resultTimeInMins = estTimeInMins - totalTimeInMins ; //calculating result time
var resultHours = Math.floor(resultTimeInMins/60); //getting number of hours. Math.floor is rounding off to lower integer
var resultMinutes = resultTimeInMins%60; //calculating number of minutes. This is like getting the remainder.


console.log("Result:", resultHours + ":" + resultMinutes);




答案 1 :(得分:1)

在操纵时间时,在毫秒基础上进行操作几乎总是一个好主意。



var Time = (function () {
    function Time(time) {
        if (time === void 0) { time = 0; }
        this.time = time;
    }
    Time.prototype.setSeconds = function (seconds) {
        if (seconds === void 0) { seconds = 0; }
        this.time += (seconds * 1000);
        return this;
    };
    Time.prototype.setMinutes = function (minutes) {
        if (minutes === void 0) { minutes = 0; }
        this.time += ((minutes * 60) * 1000);
        return this;
    };
    Time.prototype.setHours = function (hours) {
        if (hours === void 0) { hours = 0; }
        this.time += (((hours * 60) * 60) * 1000);
        return this;
    };
    Time.prototype.setDays = function (days) {
        if (days === void 0) { days = 0; }
        this.time += ((((days * 24) * 60) * 60) * 1000);
        return this;
    };
    Time.prototype.getTime = function (toString) {
        if (toString === void 0) { toString = false; }
        var t = this.time;
        var d = new Date(Math.abs(t));
        var sub = this.time < 0;
        d.setHours(d.getHours() - 1);
        d.setFullYear(0);
        var time = {
            days: Math.floor(Math.abs(this.time) / (((24 * 60) * 60) * 1000)),
            hours: d.getHours(),
            minutes: d.getMinutes(),
            seconds: d.getSeconds(),
            milliseconds: d.getMilliseconds(),
            sub: sub
        };
        //Returns in the format "DAYS:HOURS:MINUTES:SECONDS"
        if (toString === true) {
            return (sub ? '-' : '') +
                Math.abs(time.days) +
                ':' +
                Math.abs(time.hours) +
                ':' +
                Math.abs(time.minutes) +
                ":" +
                Math.abs(time.seconds);
        }
        else {
            return time;
        }
    };
    return Time;
}());
var t1 = new Time();
var t2 = new Time();
t1
    .setMinutes(357)
    .setHours(1200);
t2
    .setHours(-1)
    .setMinutes(-30);
var t3 = new Time(t1.time + t2.time);
console.log("t1", t1.getTime(true));
console.log("t2", t2.getTime(true));
console.log("t3", t3.getTime(true));
console.log("t3", t3.getTime());
&#13;
&#13;
&#13;

编辑1

我忘了包含days。在我的设置日无限期缩放(因为我不想像二月或闰年那样混乱奇怪的月份)。