I use the following code to calculate the difference between two numbers.
function differenceCalculation(num1, num2) {
if (num1 > num2) {
return num1 - num2
} else {
return num2 - num1
}
}
On document.ready
var difference = differenceCalculation(visitorTime, firstOption);
console.log({difference});
This gives for instance the following values in the console:
visitorTime = 1831
firstOption = 1900
difference = 69
But since this should return the difference in time, I need it to do the calculation with 60
as the ceiling instead of the default 100
.
A simple solution would be to minus 40
from the difference, but is this a good solution?
var difference = ( differenceCalculation(visitorTime, firstOption) - 40 );
CodePudding user response:
Just shortly after submitting and responding to the comments, I figured out a way that worked for me. Be aware though that the linked question has better answers! Which is the reason I voted to close this question.
Anyway, I made these changes to my code, and now I get the required outcome.
var difference = differenceCalculation(visitorTime, firstOption);
if ( difference >= 30 ) {
var difference = ( differenceCalculation(visitorTime, firstOption) - 40 );
}
console.log({difference});
In the console:
visitorTime = 1831
firstOption = 1900
difference = 29
And if the first 2 values where different:
visitorTime = 1901
firstOption = 2000
difference = 59
CodePudding user response:
It looks like you want to calculate in "military" time (like in "at nineteenhundred fifteen").
So, that involves converting both time indicators to hours and minutes, then doing the subtraction of each (with carry if needed), and then converting it back to military time:
const toHourMinute = military => [Math.floor(military / 100), military % 100];
const toMilitary = (hour, minute) => hour*100 minute;
function timeDifference(a, b) {
if (a > b) return timeDifference(b, a);
let [h1, m1] = toHourMinute(a);
let [h2, m2] = toHourMinute(b);
if (m2 < m1) { // Deal with a carry over
m2 = 60;
h2--;
}
return toMilitary(h2 - h1, m2 - m1);
}
var visitorTime = 1831
var firstOption = 1900
var difference = timeDifference(visitorTime, firstOption);
console.log({difference});