0

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?

mushroom126
  • 47
  • 10
  • 1
    Why not just convert both sets of values to a common denominator (say seconds) and get the difference? If it's more than 600 seconds, it's more than 10 minutes. – RobG Aug 16 '18 at 09:14
  • 1
    you can convert both to epoch seconds and then take a difference. its easier and less code – Ahmad Karim Aug 16 '18 at 09:14
  • 1
    possible duplicate [how-to-calculate-date-difference-in-javascript](https://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript) – Ahmad Karim Aug 16 '18 at 09:16
  • Possible duplicate of [How to calculate date difference in javascript](https://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript) – Liam Aug 16 '18 at 09:23

4 Answers4

1

You should calculate the time difference first, then do the logic. That way you can always show the difference regardless of the outcome of the test. To do the difference, convert to some common base like seconds or minutes, then format however suits for presentation, e.g.

function getTimeDiff(h1, m1, s1, h2, m2, s2) {
  return diff =  toSeconds(h2, m2, s2) - toSeconds(h1, m1, s1);  
}

function toSeconds(h, m, s) {
  return h*3600 + m*60 + s*1;
}

function secondsToHMS(secs) {
  function z(n){return (n<10? '0':'') + n}
  return z(secs/3600|0) + ':' +
         z((secs%3600)/60|0) + ':' +
         secs%60;
}

// Tests
[[4,23,15, 5,5,8],    // 04:23:15 vs 05:05:08
 [4,23,15, 4,25,8]].  // 04:23:15 vs 04:25:08
  forEach(function(arr) {
    var diff = getTimeDiff(...arr);
    console.log(`Diff of ${secondsToHMS(diff)} is ${diff > 600? 'more':'less'} than 10 minutes`);
 });
RobG
  • 142,382
  • 31
  • 172
  • 209
  • this worked really well, thank you! I played around with the functions and managed to get the script in the format I need. Now just trying to figure out how to apply the functions above in a for loop to an array of times. – mushroom126 Aug 16 '18 at 10:37
0

As answered here Get difference between 2 dates in JavaScript?

var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays);`
Ahmad Karim
  • 459
  • 1
  • 6
  • 17
  • but this gives the difference between two dates, whereas my code is looking at the difference between two times, specifically in minutes. – mushroom126 Aug 16 '18 at 09:27
  • dates-time is one object, you can add time fields in the date object. if you do not add any time fields it takes the time as 00:00:00 so in this case date1 is taken as ```07/13/2010 00:00:00``` – Ahmad Karim Aug 16 '18 at 09:36
0

To calculate the difference, you can replace whatever you've put below your "Calculating the difference" comment with:

//........Calculating the difference........//
if(Math.abs(d1.getTime() - d2.getTime()) <= 600000) {
    // execute your function
}

Explanation

  • getTime() function of Date object returns the date timestamp, i.e. the number of milliseconds elapsed between the 1st Jan 1970 00:00:00 UTC and the date in your object. This is much easier to use when making computations with dates, rather than separately comparating/calculating hours, then minutes and seconds... It is also a pretty common practice in sofware development.
  • Using this function, we are computing the difference in milliseconds. I'm using Math.abs() in order to ensure that this difference is always a positive number. That makes the following comparison easier.
  • Then, we just need to check whether this difference is less or equals than 10 minutes, i.e. 10 * 60 * 1000 = 600000 milliseconds.

There we go! You have now the condition you need for calling your function.

Feel free to reply if more clarification is needed.

mr.mams
  • 425
  • 4
  • 10
0

Try using parseInt() function as after appending 0 to h1, h2, m1 and m2 it is treated as a string.

if (parseInt(h1) == parseInt(h2)) {
    var diff = parseInt(m2) - parseInt(m1);
        if ((diff == 10)) {
            document.getElementById("diff").innerHTML = diff;
            move();
    }
}
Exterminator
  • 1,221
  • 7
  • 14
  • This doesn't solve his problem when the difference is less than 10 mins, and the hours are not the same. Try with this example: d1 = 2018/08/16 11:00:01 and d2 = 2018/08/16 10:58:00 – mr.mams Aug 16 '18 at 09:42