简体   繁体   中英

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.

I've noticed that the date changes to the following day (ex. Oct 1 --> Oct 2) every day at 5pm. I want to make sure this date changes at 12am every day and not 5pm. I'm wondering where the error is in my code that causes this to occur.

Here is the Javascript code I use:

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. Change the value of tzOffset to 0 and it should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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