Rik Rook
Rik Rook

Reputation: 1

Javascript time between 08:30 - 20:00

I am trying to make a message show between certain time ranges in a day but i cant make it work it either shows the first IF or doesnt show anything at all with an error i cant seem to figure out. what am i doing wrong?

var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();

if(today.getDay() == 4){
        if(hour > 8 && minute > 30 || hour < 20){
            document.getElementById('test').innerHTML = ('come today till 20:00');
        } else if (hour > 20 && hour < 0){
            document.getElementById('test').innerHTML = ('Come tomorrow till 20:00');
        } else (hour > 0 && hour < 8).document.getElementById('test').innerHTML = ('Come today from 08:00 till 20:00');
    }

figured it out thanks for the help guys :) this is how it works now.

        if(today.getDay() == 4){
        if((hour === 8 && minute > 30 || hour > 8) && hour < 20){
            document.getElementById('test').innerHTML = ('Kom vandaag langs in onze showtuin tot 20:00 uur donderdag');
        } else if (hour >= 20 && hour < 24){
            document.getElementById('test').innerHTML = ('Kom morgen langs in onze showtuin tot 20:00 uur');
        } else{
            document.getElementById('test').innerHTML = ('Kom vandaag langs in onze showtuin van 08:00 tot 20:00 donderdag');
        }
    }

Upvotes: 0

Views: 62

Answers (2)

Radek Pech
Radek Pech

Reputation: 3098

Each if can use the previous condition to its advantage which means if you correctly sort the conditions you can make it really simple:

if (hour >= 20) {
    //20:00 - 23:59
}
else if (hour > 8) {
    //9:00 - 19:59
}
else if (hour == 8 && minute >= 30) {
    //8:30 - 8:59
}
else {
    //0:00 - 8:29
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You could simplify the conditions a bit, with checking from small values to greater values, like

if (today.getDay() == 4) {
    if (hour < 8) {
        document.getElementById('test').innerHTML = 'Come today from 08:00 till 20:00';
    } else if (hour < 20) {
        document.getElementById('test').innerHTML = 'Come today till 20:00';
    } else if (hour < 24) {
        document.getElementById('test').innerHTML = 'Come tomorrow till 20:00';
    }
}

Upvotes: 2

Related Questions