如果日期少于或超过15分钟(如果日落或日出)

时间:2015-12-17 09:39:21

标签: javascript date datetime conditional

我正在尝试使用日期来获取日落日出

由于我不确定如何处理如果Else声明关于日期

我在日落时和日出时获得了数据。

但是想知道当前日期是+-15 minutes

的日落或日出时如何做条件

示例:

当前日期:2015-12-17T 17:45 :00 (或17:45至18:15之间)

日落:2015-12-17T 18:00 :00

Rusult = 日落(因为+-15 minutes

到目前为止,这是我的代码:

var SunData = {'set':'2015-12-17T09:14:56', 'rise':'2015-12-17T15:10:52'};

var date = new Date();
    date = date.getTime();

var sun_rise = new Date(SunData['rise']);
    sun_rise = sun_rise.getTime();

var sun_set = new Date(SunData['set']);
    sun_set = sun_set.getTime();

var sunRiseSetDiff = 900000; // 15 minutes

// Here
var result;
if(false) {
    result = 'sun-rise';
} else if (false) {
    result = 'sun-set';
} else {
    result = 'none';
}

https://jsfiddle.net/gd1s1o0y/

你能帮我解决一下 If Else声明吗?感谢

3 个答案:

答案 0 :(得分:2)

你的意思是

var result = 'none';
if(Math.abs(date - sun_rise) <= sunRiseSetDiff) {
    result = 'sun-rise';
}
else if(Math.abs(date - sun_set) <= sunRiseSetDiff) {
    result = 'sun-set';
}

Fiddle

答案 1 :(得分:2)

选中此fiddle

var SunData = {'set':'2015-12-17T09:14:56', 'rise':'2015-12-17T15:10:52'};

var date = new Date();
        date = date.getTime();

var sun_rise = new Date(SunData['rise']);
        sun_rise = sun_rise.getTime();

var sun_set = new Date(SunData['set']);
        sun_set = sun_set.getTime();

var sunRiseSetDiff = 900000; // 15 minutes

// Here
var sunsetResult = Math.abs( date - sun_set ) > sunRiseSetDiff ? false: true;
var sunriseResult = Math.abs( date - sun_rise ) > sunRiseSetDiff ? false: true;

if(sunriseResult) {
    result = 'sun-rise';
} else if (sunsetResult) {
    result = 'sun-rise';
} else {
    result = 'none';
}

alert(result);

答案 2 :(得分:1)

只需用评论重新编写您的函数。

&#13;
&#13;
// Always parse date strings manually, you can use a library if you want
// but a bespoke function is pretty simple if the format is guaranteed
// and is a valid date
function qParse(s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1]-1, b[2], b[3]||0, b[4]||0, b[5]||0, b[6]||0);
}
    
// The OP seemed to have sunrise and sunset transposed
var sunData = {'rise':'2015-12-17T09:14:56', 'set':'2015-12-17T15:10:52'};

// There is no need for getTime, date objects can be used in simple
// arithmetic directly
var now = new Date();
var buffer = 9e5; // 15 mintues

// Initialise result to a default string
var result = 'Not near sunrise or sunset';
    
// Change value if near sunset
if (Math.abs(now - qParse(sunData.set)) <= buffer) {
  result = "Close to sunset"; 

// Otherwise, change value if near sunrise
} else if (Math.abs(now - qParse(sunData.rise)) <= buffer) {
  result = "Close to sunrise"; 
}
    
// Show result
document.write(result);
&#13;
&#13;
&#13;