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

1

I'm working with Angular, and when I save 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 to log in, but I'm having some difficulties.

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

Does anyone have any ideas how I can do this math? I can not just take the difference of minutes and seconds, since let's say that the cookie is that the session will expire at 5:20 pm, and now it's 4:51, I'll have a difference of 31 (using the Math.abs () function) minutes , what's wrong. I would need some way to convert all this to the same format, subtract and then reconvert to minutes and seconds again.

Talez would solve if I multiplied the minutes by 60 to transform in seconds and subtract. But there is the question of the turn of the day, where the expiration can be 00:10 and the current time 23:50 making this method nonfunctional. And just as we have the turn of the day, we have the month and the year. And not every month has the same amount of days for me to go out multiplying like this.

    
asked by anonymous 02.01.2019 / 11:59

1 answer

1

I was able to do what I wanted. With the getTime () function of the Date class. Basically I get both times in milliseconds with the function and, after calculating the difference, I make 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)}')
    
02.01.2019 / 12:33