I need a helping hand in a time calculation algorithm. It is not a usual time operation, so momentjs won't help here.
In short, I have a time amount which I want to reduce another time amount, e.g.:
120:30 // total time
- 1:30 // time 2
119:00 // result
The total time is an estimated time for a task used in my app, so it isn't a 24 hours based time. The time 2 is a result of the working time, like if I worked 2 times on this task, first being 30 minutes and secund 60 minutes, so one hour and a half.
In my algorithm I can sum to total working time by minutes, but I can't implement the reduction calculation from the total time itself.
Here goes my code with commented parts:
// 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);
As you can see, until "So far so good"(line 41) everything seems to be working fine. My problem is with the calc after that. It is a mess and I can evolve it. The result in the snippet case should be 119:00. Any help would be appreciated.
1:00to500:00date itself doesn't metters.var s=(120*60+30 - (1*60+30)), M=Math.floor(s/60), S=M*60-s; [M,S]