Further down, follow one alternative answer and shortest. And also more economical in resources.
The function takes three arguments, in order:
- time 1
- time 2
- value to be compared in milliseconds (500, in this case)
If you don’t need anything generic (always 500ms), you can remove the third argument. But do not forget to exchange in all places within the function, appropriately, for 500 where there was the name of the third argument.
When converting the times to Date
, You need to put false data for time zone and day, month and year. It does not interfere with the result since these extra data are the same for both cases.
The function returns true
for cases where the difference is greater or less than the value specified in the 3rd argument. Returns false
if it is exactly and equal to the specified value.
The way to deal with the result is to the taste of the customer. If you want to use alert()
or other resources, just change.
// Tempos armazenados a serem verificados
var tempo_1 = "13:12:11";
var tempo_2 = "13:12:12";
// Função verificadora de diferença
function dif_ms(tempo_1, tempo_2, comparativo) {
// Converte os tempos para o tipo `Date` e obtme tempo total em milissegundos
var t1 = new Date("2000-01-01T" + tempo_1 + "Z").getTime();
var t2 = new Date("2000-01-01T" + tempo_2 + "Z").getTime();
// Verifica a diferença
var delta = Math.abs(t1 - t2);
// Retorna 'true' se for diferente (maior ou menor) que 500ms ou 0.5s
return delta != comparativo;
}
// Exemplo de saída
console.log("- É diferente de 500ms (ou 0,5s)? \n- " + (dif_ms(tempo_1, tempo_2, 500) ? "Sim." : "Não."));
And will you have decimal values in seconds? Can [Edit] the question and put what you have tried to do and write down the difficulty found?
– Woss
I haven’t done anything yet, I’m lost on how to start this comparison, decimal values in the second
– Stan
These 3 time parameters are hours, minutes and seconds? or minutes, seconds, milliseconds?
– Sergio
@DVD I didn’t realize how one can detect differences of less than a second if the accuracy degree of the input is 1 second (in case it is
hh:mm:ss
). Hence the doubt whether the last parameter would be milliseconds...– Sergio