I wrote the following script to find the time difference between two time values and execute a function when the difference is 10 minutes. In the script, variables h1, m1 and s1 are the hour, minute and second values of the first time, and h2, s2 and m2 are those of the second.
For example
h1 = 10
m1 = 55
s1 = 00
h2 = 11
m2 = 05
s2 = 00
The script currently checks to see if h1 is equal to h2. If it is, then it finds the difference between m2 and m1. If this difference is 10, it executes the function.
//........setting the current time........//
var d1 = new Date();
var h1 = d1.getHours();
var m1 = d1.getMinutes();
var s1 = d1.getSeconds();
//if the hour, minute or second is a single digit number, add a zero before it//
if (h1 < 10) {
h1 = "0"+ h1;
}
if (m1 < 10) {
m1 = "0" + m1;
}
if (s1 < 10) {
s1 = "0" + s1;
}
var now = h1 + ":" + m1 + ":" + s1;
//........setting the target time........//
var d2 = new Date(2018, 8, 16, 11, 05, 00);
var h2 = d2.getHours();
var m2 = d2.getMinutes();
var s2 = d2.getSeconds();
//if the hour, minute or second is a single digit number, add a zero before it//
if (h2 < 10) {
h2 = "0" + h2;
}
if (m2 < 10) {
m2 = "0" + m2;
}
if (s2 < 10) {
s2 = "0" + s2;
}
var time = h2 + ":" + m2 + ":" + s2;
//........Calculating the difference........//
if (h1 == h2) {
var diff = m2 - m1;
if ((diff == 10)) {
document.getElementById("diff").innerHTML = diff;
move();
}
}
However, I've realised this doesn't always work, like with the example times above. When the hour values aren't the same, the script doesn't calculate the time difference. Is there a way I can overcome this?