如何检查日子是否日复一日?

时间:2017-02-28 09:53:45

标签: javascript jquery

如何查看数组中的日期是否日复一日?

var days = ['2017-02-28', '2017-03-01', '2017-03-02', '2017-03-03']; //should return true

var days2 = ['2017-02-28', '2017-03-02', '2017-03-03', '2017-03-04']; //should return false

4 个答案:

答案 0 :(得分:3)

您可以使用以下代码实现您的目标:



var days = ['2017-02-28', '2017-03-01', '2017-03-02', '2017-03-03']; //should return true
var days2 = ['2017-02-28', '2017-03-02', '2017-03-03', '2017-03-04']; //should return false
var days3 = ['2017-02-28', '2017-03-01', '2017-04-02', '2017-04-03']; // should also return false

function dayCheck(daysArray) {
  for (var i = 1; i < daysArray.length; i++) {
    var d = new Date(daysArray[i - 1]);
    d.setDate(d.getDate() + 1);
    if (new Date(daysArray[i]).getTime() != d.getTime())
      return false;
  }
  return true;
}
console.log(dayCheck(days));
console.log(dayCheck(days2));
console.log(dayCheck(days3));
&#13;
&#13;
&#13;

基本上,你拿每个日期,你递增它并检查它是否与数组中的下一个日期相匹配。

<强>更新

正如所指出的,使用getDate()会因days3中的数组值而失败,因此我将代码更改为使用getTime(),这似乎更强大。

答案 1 :(得分:2)

像这样,

function areDatesSequential(days) {
    var seq = true;
    var d = new Date(days[0]);
    for(var i=1;i<days.length;i++) {
        d.setDate(d.getDate() + 1);
        var d2 = new Date(days[i]);
        if(d.getDate() != d2.getDate()
            || d.getMonth() != d2.getMonth()
            || d.getFullYear() != d2.getFullYear()) {
            seq = false;
        }
    }

    return seq;
}

答案 2 :(得分:1)

试试这个

var days = ['2017-02-28', '2017-03-01', '2017-03-02', '2017-03-03'];
// convert to timestamp
var timestamps = days.map(function(day){
     var date = new Date(day);
     return date.getTime();
});
console.log(timestamps);
var result = true;
for(var i = 1 /*from second el*/; i < timestamps.length; i++) {
    // console.log(timestamps[i] - timestamps[i - 1]);
    if (timestamps[i] - timestamps[i - 1] !== 86400000/* one day in milliseconds*/) {
        result = false;
        break;
    }
}
console.log('res', result);

答案 3 :(得分:1)

<Description/>