You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用localStorage计算用户上次访问网站的间隔天数

实现上次访问间隔天数显示(基于localStorage)

核心问题修正思路

你现在的代码逻辑有两个关键问题:一是错误用字符串做时间减法,二是搞反了存储对象——应该存本次访问的时间戳,下次访问时用当前时间减去这个存储值来计算间隔,而不是直接存差值。

修正后的完整代码

HTML(无需修改)

<article>Days since your last visit:<span class="timeBetween"></span></article>

JavaScript(修正逻辑)

const visitsDisplay = document.querySelector('.timeBetween');
// 获取当前时间的毫秒级时间戳
const currentTime = Date.now();
// 从localStorage读取上次访问的时间戳,首次访问时为null
const lastVisitTime = localStorage.getItem('lastVisit');

if (lastVisitTime) {
  // 计算时间差并转换为天数(1天 = 1000毫秒*60秒*60分*24小时)
  const timeDiffMs = currentTime - parseInt(lastVisitTime);
  const daysBetween = Math.floor(timeDiffMs / (1000 * 60 * 60 * 24));
  
  // 插入计算结果
  visitsDisplay.textContent = ` ${daysBetween} day(s)`;
} else {
  // 首次访问的提示
  visitsDisplay.textContent = ' This is your first visit!';
}

// 更新localStorage,把本次访问时间存进去
localStorage.setItem('lastVisit', currentTime);

关键逻辑说明

  • 存储时间戳而非差值:Date.now()返回当前时间的毫秒数,存在lastVisit键下,下次访问直接读取这个值做计算。
  • 时间差转换:通过毫秒数差值除以一天的毫秒总数,再用Math.floor()取整,得到完整的间隔天数。
  • 首次访问判断:如果localStorage里没有lastVisit记录,直接显示首次访问提示。

内容的提问来源于stack exchange,提问作者Blossompot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:57:26