Timer with active session time: Cookie expiration time - autal moment

Asked

Viewed 304 times

1

I am working with Angular and, when I store the access token in a cookie, I also save (in another cookie) its expiration time (30 minutes). I want to make a timer that shows the user how long he still has session, but I’m having some difficulties.

I want the timer to work as follows: Whenever someone enters the initial component of Angular, the moment when the token expires is picked up in the cookie and a calculation based on the current moment is made and the remaining minutes and seconds are saved in two variables of type number. Which will update and decrease automatically with the setInterval function().

Does anyone have any idea how I do this math? I can’t just take the difference of minutes and seconds, because let’s say the cookie is that the session will expire at 17:20, and now it’s 16:51, I’ll have a difference of 31 (using the Math.abs()) minutes, which is wrong. I would need somehow to convert all this to the same format, subtract and then reconvert to minutes and seconds again.

Maybe it would if I multiplied the minutes by 60 to turn it into seconds and subtract. But there is the question of the turn of the day, in which the expiration can be 00:10 and the current time 23:50 making this method non-functional. And just as we have the turn of the day, we have the turn of the month and the turn of the year. And not every month has the same amount of days for me to multiply so.

1 answer

1


I was able to do what I wanted. With the getTime() function of the Date class. I basically take both times in milliseconds with the function and, after calculating the difference, turn the difference

console.log(`Expiração ${expirationDate.getMinutes()}:${expirationDate.getSeconds()}`)
console.log(`Agora ${new Date().getMinutes()}:${new Date().getSeconds()}`)

let difference = expirationDate.getTime() - new Date().getTime()

console.log(`Diferença ${Math.trunc((difference / 1000)  / 60)}:${Math.trunc((difference / 1000) % 60)}`)

Browser other questions tagged

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