js获取一组日期中最近连续的天数

function lianxuDay(){
     var arr = [
     '2016/02/28',
     '2016/02/29', 
     '2016/02/26', 
     '2017/02/27',
     '2017/02/28'
    ];
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth()+1;
    var d = date.getDate();
    var today = y+'/'+m+'/'+d;
    today = '2017/03/01';***//这边是获取到当天的日期***
    console.log(today);
    //转时间戳 
    function time(date){
     return new Date(date); 
    }
    var num = 0;//声明计数变量;
    var le = arr.length;//数组长度;
    //console.log(time(today)-time(arr[le-1]));
    if(time(today)-time(arr[le-1])==86400000)
       //日期时间戳相差一天则连续,此法虽笨,但实用;判断当前日期与最近一天
    {
     num=2;//满足条件,连续2天;
     //然后对数组循环判断,满足则num++;否则中断循环;
     for(var i=le; i>0; i--){
      if(time(arr[i-1])-time(arr[i-2])==86400000){
       num++; 
      }else{ 
       break;//如果只要找出所有连续的天数,不需要中断
      }
      console.log(num);
     } 
    }else{
     console.log('第一天');
    }
   }
   lianxuDay();

感谢分享 https://www.jb51.net/article/114669.htm

猜你喜欢

转载自blog.csdn.net/qq_32963841/article/details/81669059