开发者

Javascript time if statement 8.30am

I have a javascript function called showbanner() which is designed to开发者_如何学运维 change the src of an image based on our opening hours. It's worked well for ages...

function showbanner() { 
    now = new Date();
    t = now.getUTCHours();
    m = now.getUTCMinutes();
    if (t>9 && t<17) document.getElementById('theImg').src="/Img/Open.png"; 
    else document.getElementById('theImg').src="/Img/Closed.png";
}

However, we've just changed our opening hours from 9am - 5pm to 8.30am - 5pm and I can't for the life of me work out how to express 8.30am in the above if statement!

Could I do:

 if ((t>8 && t<9 && m>30) && t<17)....

?????

Thanks in advance for any help!

Cheers, Matt


You could make a variable which stores the time in military time format.

function showbanner() { 
    var now = new Date();
    var t = now.getUTCHours();
    var m = now.getUTCMinutes();
    var mil = 100*t+m; // Military time
    if (mil >= 830 && mil <= 1700) { // Between 8:30 AM and 5:00 PM
        document.getElementById('theImg').src="/Img/Open.png"; 
    } else {
        document.getElementById('theImg').src="/Img/Closed.png";
    }
}

That could make it easier to make future changes.


function showbanner() { 
    var now = new Date();
    var t = now.getUTCHours();
    var m = now.getUTCMinutes();
    if ((t > 8 || t === 8 && m <= 30) && t < 17) document.getElementById('theImg').src="/Img/Open.png"; 
    else document.getElementById('theImg').src="/Img/Closed.png";
}


Try this(convert 8:30 to seconds which is 510 and check if (t*60)+m is greater than that):

function showbanner() { 
    now = new Date();
    t = now.getUTCHours();
    m = now.getUTCMinutes();
    if (((t*60) + m) >510 && t<17) 
        document.getElementById('theImg').src="/Img/Open.png"; 
    else
        document.getElementById('theImg').src="/Img/Closed.png";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜