计算日落和日出时间后确定白天还是夜晚

问题描述 投票:0回答:2

我已经根据用户位置成功计算了日出和日落时间,并将小时和分钟存储在数组中。所以小时是第零个元素,分钟是第一个元素,看起来像这样

var sunrise = [09, 23];
var sunset = [20, 49];

我想做的是在黎明时做一些事情,然后在白天做一些单独的事情,然后在黄昏时做一些单独的事情,然后在晚上做一些单独的事情。这么说吧,现在我想提醒一下现在是一天中的哪一段时间。

我将黎明定义为日出前1小时到日出后1小时。白天是黎明和黄昏之间的一天。黄昏为日落前 1 小时至日落后 1 小时。夜晚是指黄昏和黎明之间,或者更简单地说是其他任何东西。

我尝试使用下面的 if 语句来执行此操作,但即使日出和日落正确,它也会说晚上是黄昏。

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"); 
}
javascript jquery
2个回答
2
投票

我认为,你应该像这样将时间转换为分钟:

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

然后测试你的条件:

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) {
    alert("dusk")
} else if (now_m > sunrise_m - 60 && now_m <= sunrise_m + 60) {
    alert("dawn")
} else if (now_m > sunrise_m + 60 && now_m <= sunset_m - 60) {
    alert("day")
} else {
    alert("night")
}

http://jsfiddle.net/12m8ty2y/


0
投票

要回答您的确切问题标题:根据当前时间、日出和日落确定白天或夜晚:

const mod = (n, m) => ((n % m) + m) % m; // Fix negative modulo.
const isDay = (h, rise, set) => mod(h - rise, 24) < mod(set - rise, 24);

// Test: sunruse is at 06:00 and sunset is at 21:00
for (let i = 0; i < 24; i++) console.log(i +" "+ isDay(i, 6, 21));

© www.soinside.com 2019 - 2024. All rights reserved.