gpt4 book ai didi

javascript - 如何计算并显示自用户首次访问该网站以来经过的小时数?

转载 作者:行者123 更新时间:2023-12-03 10:06:58 25 4
gpt4 key购买 nike

我想知道如何完成hoursSinceFirstVisit()函数。另外我会在 HTML 页面中显示什么?

$(document).ready(function() {

startTimer();

});

function startTimer() {
setInterval(function() {
var text = "It's been " + hoursSinceFirstVisit() + " hours since you first visited.";
$('#timer').text(text);
}, 1000);
}

function hoursSinceFirstVisit() {

// use local storage to calculate the time elapsed between the user's first visit and now

}

/**
* Calculates the number of hours between two dates to 3 decimal places
* @param {Date|string} earlier The earlier date.
* @param {Date|string} later The later date.
*/
function hoursBetweenDates(earlier, later) {
var later = typeof later == 'string' ? new Date(later) : later;
var earlier = typeof earlier == 'string' ? new Date(earlier) : earlier;
var elapsed = later - earlier;
console.log(earlier, later, elapsed);
return (elapsed / 1000 / 60 / 60).toFixed(3);
}

我想知道如何完成hoursSinceFirstVisit()函数。另外我会在 HTML 页面中显示什么?

最佳答案

你可以试试这个:

function hoursSinceFirstVisit() {
var d = new Date(localStorage.getItem("timestamp")); //get timestamp from localStorage
d = d.getTime(); //convert to milliseconds
var D = new Date().getTime();
var diff = D - d; //difference in milliseconds
var hours = (diff / 60000) / 60;
return hours
}

关于javascript - 如何计算并显示自用户首次访问该网站以来经过的小时数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30317356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com