Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - JavaScript日期从1小时开始(Javascript Date starts with 1 hour)

I'm trying to create a counter that shows how much time you've spent on the site and I use sessionStorage to access the Date object from multiple pages.(我正在尝试创建一个计数器,该计数器显示您在网站上花费了多少时间,并且我使用sessionStorage从多个页面访问Date对象。)

The problem is that the counter starts at 01:00:00 even though I initialized the Date with 00:00:00.(问题是即使我使用00:00:00初始化了Date,计数器也从01:00:00开始。)

Here is my code:(这是我的代码:)

function checkTime(){
    if(document.getElementById("clock")[13] == ''){
        var d = new Date('2010-06-11T00:00:00');
        sessionStorage.setItem('time', d);
    }
}

function updateTime(){
    checkTime();
    var nDate = new Date(sessionStorage.getItem('time'));
    nDate.setSeconds(nDate.getSeconds() + 1);
    sessionStorage.setItem('time', nDate);
    var hours = (nDate.getHours()<10 ? "0" : "") + nDate.getHours();
    var minutes = (nDate.getMinutes()<10 ? "0" : "") + nDate.getMinutes();
    var seconds = (nDate.getSeconds()<10 ? "0" : "") + nDate.getSeconds();
    var timeString = hours + ":" + minutes + ":" + seconds;
    document.getElementById("clock").innerText = timeString;

}
setInterval(updateTime, 1000);
  ask by cazhjo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It starts at 01:00 due to your timezone (UTC +1 CET Central European Time, Stockholm).(根据您所在的时区(UTC +1 CET中欧时间,斯德哥尔摩),它从01:00开始。)

Create your date in the following manner:(通过以下方式创建日期:)

 const utcDate = new Date(Date.UTC(2019, 5, 11, 0, 0, 0)); // second param is the month-index, it start at 0, so 5 means june console.log(utcDate); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...