实现用户末次访问检测时,调用toLocaleString后出现d.getFullYear报错
问题解决:
d.getFullYear is not a function 错误处理 错误原因
你把toLocaleString()的结果直接赋值给了变量d,但这个方法返回的是格式化好的字符串,不是Date对象,自然调用不了getFullYear()、getMonth()这些Date专属方法。
修复方案
先创建原始的Date对象,用它来生成你需要的strDate和strTime;如果需要本地化日期显示,再单独用toLocaleString()处理(按需使用)。
修改后的代码
var visitDetection = document.querySelectorAll('.visit-detection')[0]; if(visitDetection){ var neverVisited = document.querySelectorAll('.never-visited')[0]; var beforeVisited = document.querySelectorAll('.before-visited')[0]; var visitBeforeTime = document.querySelectorAll('.visit-before-time')[0]; var lastVisitValue = localStorage.getItem(pwaName+'-Last-Visited'); var options = { year: "numeric",day: "numeric", month: "long" }; // 先创建原始Date对象 var d = new Date(); // 用Date对象生成自定义格式的日期时间字符串 var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate(); var strTime = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); // 如果需要本地化日期字符串,单独生成(示例,根据需求调整) var localDate = d.toLocaleString("fa-IR", options); if(!lastVisitValue){ neverVisited.style.display="block"; beforeVisited.style.display="none"; localStorage.setItem(pwaName+'-Last-Visited', 'آخرین بازدید شما ' + strDate +' در '+ strTime) } else { neverVisited.style.display="none" beforeVisited.style.display="block" visitBeforeTime.append(lastVisitValue) localStorage.setItem(pwaName+'-Last-Visited', 'آخرین بازدید شما ' + strDate +' در '+ strTime) } }
额外说明
如果你的需求是把存储的日期改成本地化格式,直接把strDate替换成localDate即可,不需要再手动拼接年/月/日。
内容的提问来源于stack exchange,提问作者Amin
相关产品推荐
相关产品推荐

