简体   繁体   English

在javascript中显示日期和时间的代码会迭代到每天下午5点

[英]Code that displays date and time in javascript iterates to the next day at 5pm every day

I have some javascript code that I use to display the date and time on an html web page. 我有一些JavaScript代码,可用于在html网页上显示日期和时间。

I've noticed that the date changes to the following day (ex. Oct 1 --> Oct 2) every day at 5pm. 我注意到,日期更改为每天下午5点的第二天(例如10月1日-> 10月2日)。 I want to make sure this date changes at 12am every day and not 5pm. 我想确保此日期在每天的凌晨12点而不是下午5点更改。 I'm wondering where the error is in my code that causes this to occur. 我想知道错误在我的代码中会导致这种情况发生。

Here is the Javascript code I use: 这是我使用的Javascript代码:

function GetClock(){
    var tmonth=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var d=new Date();
    var nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getFullYear();


    document.getElementById('date').innerHTML=""+tmonth[nmonth]+" "+ndate+", "+nyear+"";
}

function GetTime(city, offset){
    var tzOffset = -7;

    var d=new Date();
    var dx=d.toGMTString();
    dx=dx.substr(0, dx.length -3);
    d.setTime(Date.parse(dx))
    d.setHours(d.getHours() + tzOffset);

    var nhour=d.getHours(),nmin=d.getMinutes(),ap;
    if(nhour==0){ap=" AM";nhour=12;}
    else if(nhour<12){ap=" AM";}
    else if(nhour==12){ap=" PM";}
    else if(nhour>12){ap=" PM";nhour-=12;}

    if(nmin<=9) nmin="0"+nmin;

    document.getElementById('time').innerHTML=""+nhour+":"+nmin+ap+"";
}

window.onload=function(){
    GetTime();
    setInterval(GetTime,1000);
    GetClock();
    setInterval(GetClock,1000);
}

You have a timezone offset of -7 in there. 您的时区偏移量为-7。 Change the value of tzOffset to 0 and it should be fine. tzOffset的值更改为0,就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM