【问题标题】:Determining if day or night after calculating sunset and sunrise times在计算日落和日出时间后确定是白天还是黑夜
【发布时间】:2014-08-17 22:26:05
【问题描述】:

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


    【解决方案1】:

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

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 2019-11-07
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2011-06-23
      相关资源
      最近更新 更多