Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate difference between two timestamps using javascript

I have two timestamps and I need difference between them in hours. How to calculate them.

var resolution
var EndTime = 1541092163000
var StartTime = 1541077763000
resolution = slaEndTime - slaStartTime
var resolutionTime = ((resolution / (1000 * 60)) % 60)
like image 962
arun kumar Avatar asked Sep 26 '26 14:09

arun kumar


2 Answers

You just need to divide rather than do times and modulus

/1000 will convert it to seconds

the first /60 will convert to minutes

and the last /60 hours

var resolution
var EndTime = 1541092163000
var StartTime = 1541077763000
resolution = EndTime - StartTime
var resolutionTime = (((resolution / 1000) / 60)/ 60)
console.log(resolutionTime)

Or you can use momentjs https://momentjs.com/

like image 122
George Avatar answered Sep 28 '26 02:09

George


See the snippet below. You need to divide by 1000 then by 60 and then by 60 again to get the hours. In short you need do divide by 1000*60*60=3600000.

var endTime = 1541092163000;
var startTime = 1541077763000;
var differenceInMiliseconds = endTime - startTime;
var differenceInSeconds = differenceInMiliseconds / 1000;
var differenceInMinutes = differenceInSeconds / 60;
var differenceInHours = differenceInMinutes / 60;
console.log(differenceInHours);

// or in short
console.log((endTime - startTime) / 3600000);
like image 41
Oram Avatar answered Sep 28 '26 02:09

Oram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!