compute hours with javascript

Asked

Viewed 1,047 times

-2

I want to calculate the time taken between two hours:

var h1 = 23:14:32;
var h2 = 22:55:27;
var total = h1 - h2;

the return I get is Nan.

  • Actually this is not even to execute, this syntax does not exist. What you want to do is extraordinarily more complex and people often use libraries for that, or do tricks that work much more or less, therefore unreliable.

2 answers

3

function formatar_segundos(h,min,s) {
 return (h*3600)+(min*60)+(s);
}

var data = formatar_segundos(23,14,32);
var data2 = formatar_segundos(22,55,27);

var diferenca = data_format(data-data2);
function data_format(s) {
 this.h = Math.floor(s/3600);
 this.min = Math.floor((s - (this.h*3600))/60);
 this.s = s - (Math.floor(s/60)*60);
 return this.h + "h "+ this.min + "min "+this.s + "s";
}

-1

It is returning Nan global property, which is a special value meaning Not-A-Number (not a number), since vc is setting only strings in variables.

Use this function to start and read jquery API documentation that can help you. :)

Jquery Documentation: https://api.jquery.com/

Nan = https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

function myFunction() {
  var d = new Date(); //seta o objeto Date
  var n = d.getHours() -2; //subtraí 2 horas da hora atual
  return n; 
}
console.log(myFunction()); //exibi "apenas" o valor da hora atual menos 2hrs (sem os minutos)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.