美文网首页
获取最近几天日期的方法,包括前七天或者后七天,或者前三天后三天连

获取最近几天日期的方法,包括前七天或者后七天,或者前三天后三天连

作者: MrOldK | 来源:发表于2018-04-09 22:17 被阅读301次

第一种方法:new Date().getTime()根据天数加减毫秒数

    //获取前七天的日期(假设当前日期为4.9号)
    function getPreIndexDate(){
      var ot = new Date().getTime(),
      da = [],
      nd,
      month,
      day;
      for(var i=7;i>0;i--){
          nd = ot - i*24*60*60*1000;
          month = new Date(nd).getMonth()+1,
          day = new Date(nd).getDate();
          da.push(month+'.'+day);
      }
      return da;
  }//["4.2", "4.3", "4.4", "4.5", "4.6", "4.7", "4.8"]

      //获取后七天的日期(假设当前日期为4.9号)
      function getAfterIndexDate(){
      var ot = new Date().getTime(),
      da = [],
      nd,
      month,
      day;
      for(var i=1;i<8;i++){
          nd = ot + i*24*60*60*1000;
          month = new Date(nd).getMonth()+1,
          day = new Date(nd).getDate();
          da.push(month+'.'+day);
      }
      return da;
  }//["4.10", "4.11", "4.12", "4.13", "4.14", "4.15", "4.16"]
      //以上两种方法基本是一样的,只不过for循环体加减时间的差别。

      //获取三天前到三天后,连续七天的日期(假设当前日期为4.9号)
      function getSiblingIndexDate(){
          var ot = new Date().getTime(),
              da = [],
              nd,
              month,
              day;
          for(var k=3;k>0;k--){
              nd = ot - k*24*60*60*1000;
              month = new Date(nd).getMonth()+1,
              day = new Date(nd).getDate();
              da.push(handleTime(month)+'.'+handleTime(day));
          }
          var nowMonth = new Date().getMonth()+1,
              nowDate = new Date().getDate();
          da.push(handleTime(nowMonth)+'.'+handleTime(nowDate));
          for(var i=1;i<4;i++){
              nd = ot + i*24*60*60*1000;
              month = new Date(nd).getMonth()+1,
              day = new Date(nd).getDate();
              da.push(handleTime(month)+'.'+handleTime(day));
          }
          return da;
      }  // ["04.06", "04.07", "04.08", "04.09", "04.10", "04.11", "04.12"]

      //如果需要处理一下单日日期,例如将4月9日处理成4月09日,则加上一下方法
      function handleTime(d){
          if(d.toString().length == 1){
              d = '0'+d;
          }
          return d;
      }
      //handleTime(9) == 09

第二种方法:setDate()

//假设当前日期为4.9号
function date(num){
  var date = new Date(); //当前日期
  var newDate = new Date();
  newDate.setDate(date.getDate() + num);
  //官方文档上虽然说setDate参数是1-31,其实是可以设置负数的
  var time = (newDate.getMonth()+1)+"."+newDate.getDate();
  return time;
}
//date(-365)==2017.4.9
//date(-7)==2018.4.2
//date(7)==2018.4.16

当然,你也可以把以上的getSiblingIndexDate()方法继续封装一下,在此不多做处理

相关文章

网友评论

      本文标题:获取最近几天日期的方法,包括前七天或者后七天,或者前三天后三天连

      本文链接:https://www.haomeiwen.com/subject/tmswhftx.html