确保JavaScript倒计时时钟不超过59秒/分钟

时间:2016-08-19 03:04:40

标签: javascript

如果之前有过类似的问题我很抱歉 - 我在SO上找不到它。

我在纯JS中构建了一个倒计时钟,它将倒计时开放时间(周五,周六,周日及其余工作日不同)。我也偏移了AEST时区,无论你在任何时区访问什么互联网设备,时间都是恒定的。

效果很好!虽然我正在努力简化代码。我今天早上注意到的一个小错误就是它喜欢从60秒和60分钟倒数,而不是让它们转换到下一个时间单位。 (即倒计时今天早上10点开始计时到下午5点,开始时间为6小时,60分钟 - 绝对应该是7个小时!)。

Anwyay,这是我的代码:

function ShowTime() {
    //access system clock and get the time
    var aest = new Date();
    var localTime = aest.getTime();

    //obtain local UTC offset and convert to msec
    var localOffset = aest.getTimezoneOffset()*60000;

    //Get total UTC time in msec
    var utc = localTime + localOffset;
    //obtain and add destination UTC time offset (Brisbane, Australia +10)
    var offset = 10;
    var brisbane = utc + (3600000*offset);
    var brisDay = new Date(brisbane);
    brisDay = brisDay.getDay();
    //Set weekend days with different opening hours
    //Set numbers representing weekend days - 0 for Sunday, 6 for Saturday
    if (brisDay===0 || brisDay===5 || brisDay===6) {
        var hoursBase = 16
        var hoursBefore = 6;
    }
    else {
        var hoursBase = 19;
        var hoursBefore = 9;
    }

    //convert msec value (with timezone offset) to datetime string variables
    var consTime = new Date(brisbane);
    var brisHours = hoursBase-consTime.getHours();
    var brisMinutes = 60-consTime.getMinutes();
    var brisSec = 60-consTime.getSeconds();

    //complete string for offset AEST local time
    //show CLOSED message if past closing time
    if (brisHours<0 || brisHours>hoursBefore) {
    var timeLeft = "<strong style='background-image:url()'>The SLQ building is currently closed.</strong>";
    } else if (brisHours<1 || brisHours>hoursBefore) {
        var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
    } else if (brisHours<2 || brisHours>hoursBefore) {
        var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
    } else if (brisHours<3 || brisHours>hoursBefore) {
        var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
    }
        else {
    var timeLeft = "SLQ will be open for another<br /><strong>" +brisHours+' hrs '+brisMinutes+' min '+brisSec+' sec'+ "</strong> today";
    }

    //output adjusted time into page
    document.getElementById("countdown").innerHTML = timeLeft;
}

//Setup variable to update on setInterval function every 1000 milliseconds
var countdown = setInterval(ShowTime ,1000);

这是一个有效的JS小提琴:https://jsfiddle.net/coolwebs/pbno1jhe/1/

我已经调查了这个问题,看起来好像我的问题在于我已经设置了

var brisMinutes = 60-consTime.getMinutes();
var brisSec = 60-consTime.getSeconds();

当我将这些数值更改为&#34; 59&#34; - 就像我提供的JS Fiddle一样 - 它似乎解决了这个问题,但似乎与计算机时钟略有不同。

我认为我接触不正确,所以有人可以就此事向我发表意见吗?

0 个答案:

没有答案