How do I go about displaying the amount of hours since the last time the user visited the webpage? I want to do this in Javascript preferably, but JQuery is fine too.
Asked
Active
Viewed 1,115 times
0
-
You can't possibly do that with client side script. At least for a long term. Try storing the time in your server for that. – Shah Abaz Khan Feb 07 '17 at 08:27
-
You can store the last visit time as a cookie then read from it and do some math to figure it out. – Woowing Feb 07 '17 at 08:29
-
1You just answered your own question if you want to do it client side. – urbz Feb 07 '17 at 08:40
-
1@Woowing what if the user uses another browser/computer? – Shah Abaz Khan Feb 07 '17 at 08:47
1 Answers
1
Assuming you have getCookie
and setCookie
functions:
const lastVisit = getCookie('lastVisitTime');
const now = Date.now();
if (lastVisit) {
const hoursSinceLastTime = Math.ceil((parseInt(lastVisit) - now) / 3600);
alert(`It's been ${hoursSinceLastTime} hour(s) since you last visited us.`);
}
setCookie('lastVisitTime', now);
-
-
-
1It will work if you have the corresponding `setCookie` (3-arity usually) and `getCookie` functions. I linked you a stack overflow question with many implementations to chose from. – lleaff Feb 07 '17 at 09:12
-
1