Рома Бойко
Рома Бойко

Reputation: 77

How to check if it's nighttime in Javascript?

I've wrote a function which returns true/false depending on whether it's nighttime or not.

isNight() {
    var date = new Date();
    return (date.getHours() > 22 && date.getHours() < 6);
}

But it doesn't work as expected. Can somebody help me figure out what's wrong?

Upvotes: 0

Views: 981

Answers (4)

srimaln91
srimaln91

Reputation: 1316

Below is my solution for this.

function isNight() {
    var hours = new Date().getHours()
    var isNightTime = hours < 6 || hours > 22
    return isNightTime;
}

Upvotes: 0

CodeF0x
CodeF0x

Reputation: 2682

You where missing the function in front of your function name, that throws error number one.

Secondly, you've got a logical error. A number can't be greater than 22 and lower than 6 at the same time. Check if the number is greater than 22 or lower than 6.

function isNight() {
  var date = new Date();
  return (date.getHours() > 22 || date.getHours() < 6);
}
console.log(isNight());

Upvotes: 1

user2693928
user2693928

Reputation:

function isNight() {
    var date = new Date();
    return (date.getHours() > 22 || date.getHours() < 6);
}

Upvotes: 1

sandyJoshi
sandyJoshi

Reputation: 763

Try using || instead of &&

function isNight() {
    var date = new Date();
    return (date.getHours() > 22 || date.getHours() < 6);
}

Upvotes: 1

Related Questions