I have to calculate the difference between 2 timestamps. Also can you please help me with conversion of a string into timestamp. Using plain javascript only. NO JQUERY.
Here's my function:
function clearInactiveSessions()
{
alert("ok");
<c:if test="${not empty pageScope.sessionView.sessionInfo}">
var currentTime = new Date().getTime();
alert("curr:"+currentTime);
var difference=new Date();
<c:forEach items="${pageScope.sessionView.sessionInfo}" var="inactiveSession">
var lastAccessTime = ${inactiveSession.lastUpdate};
difference.setTime(Maths.abs(currentTime.getTime()-lastAccessTime.getTime()));
var timediff=diff.getTime();
alert("timediff:"+timediff);
var mins=Maths.floor(timediff/(1000*60*60*24*60));
alert("mins:"+mins);
if(mins<45)
clearSession(${item.sessionID});
</c:forEach>
</c:if>
}
If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.
Here, first, we are defining two dates by using the new date(), then we calculate the time difference between both specified dates by using the inbuilt getTime(). Then we calculate the number of days by dividing the difference of time of both dates by the no. of milliseconds in a day that are (1000*60*60*24).
i am posting my own example try implement this in your code
function timeDifference(date1,date2) {
var difference = date1.getTime() - date2.getTime();
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);
console.log('difference = ' +
daysDifference + ' day/s ' +
hoursDifference + ' hour/s ' +
minutesDifference + ' minute/s ' +
secondsDifference + ' second/s ');
}
Based on the approved answer:
function(timestamp1, timestamp2) {
var difference = timestamp1 - timestamp2;
var daysDifference = Math.floor(difference/1000/60/60/24);
return daysDifference;
}
A better alternative would be using window.performance API.
const startTime = window.performance.now()
setTimeout(()=>{
const endTime = window.performance.now()
console.log("Time Elapsed : ",endTime-startTime) // logs ~2000 milliseconds
}, 2000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With