Search code examples
javascriptjquery

Determine day or night given sunset and sunrise times


I've successfully calculated the sunrise and sunset times based on user location and I store the hours and minutes in an array. So the hours is the zeroth element and the minutes are the first, looking like this var sunrise = [09, 23]; and var sunset = [20, 49];

What I want to do is do something when it is dawn, then something separate when day, then something separate when dusk, and something separate when night. let's just say, for now, I want to alert what segment of the day it is.

I define dawn as 1 hour before sunrise to 1 hour after sunrise. Day as inbetween dawn and dusk. Dusk as 1 hour before sunset until 1 hour after sunset. And night as between dusk and dawn or more simply anything else.

I've tried doing this with if statements as below, but even when the sunrise and sunset are correct, it says it is dusk in the night time.

if(hours>(sunset[0]-1) && (hours<=sunset[0]+1 && minutes<=sunset[1])){
    alert("dusk");
}
else if(hours>(sunrise[0]-1) && (hours<=sunrise[0]+1 && minutes<=sunrise[1])){
    alert("dawn");
}
else if((hours>sunrise[0]+1 || (hours===sunrise[0]+1 && minutes>sunrise[1])) && (hours<sunset[0]-1) || (hours===sunset[0]-1 && minutes<sunset[1])){
    alert("day");
}
else if(hours>sunset[0]+1 || (hours === sunset[0]+1 && minutes>sunset[1]) && (hours<sunrise[1]-1 || (hours===sunrise[1]-1 && minutres<sunrise[1]))){
    alert("night");
}
else{
    alert("night"); 
}

Solution

  • I think, you should convert your time to minutes like so:

    var sunrise_m = sunrise[0] * 60 + sunrise[1]
    

    and then test your conditions:

    var sunrise = [09, 23]
    var sunset = [20, 49];
    
    var sunrise_m = sunrise[0] * 60 + sunrise[1]
    var sunset_m = sunset[0] * 60 + sunset[1]
    
    var now = new Date()
    var now_m = now.getHours() * 60 + now.getMinutes()
    
    if (now_m > sunset_m - 60 && now_m <= sunset_m + 60) {
      console.log("dusk");
    } else if (now_m > sunrise_m - 60 && now_m <= sunrise_m + 60) {
      console.log("dawn");
    } else if (now_m > sunrise_m + 60 && now_m <= sunset_m - 60) {
      console.log("day");
    } else {
      console.log("night");
    }