倒序列出两个日期之间的月份

最终效果图

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">
    <title>test</title>
    
</head>
<body>
 <select id="selectTime">
 </select>
 <script type="text/javascript">
 var oSelect = document.getElementById('selectTime');
  initSelectTime('2014-10','2015-10');

  function initSelectTime(startTime,today){
    var startTime = new Date(startTime),
        endTime = new Date(today);
    var yearStart = startTime.getFullYear(),
        yearEnd = endTime.getFullYear(),
        monthStart = startTime.getMonth(),
        monthEnd = endTime.getMonth();
    var str = '';
    if(startTime.getTime()>endTime.getTime()){
       //getData(yearEnd+'-'+monthEnd);
       str += '<option value="'+yearStart+'-'+monthStart+'">'+monthStart+'月01日 - '+monthStart+''+getLastDay(yearStart,monthStart)+'日</option>';
       oSelect.innerHTML = str;
       return;
    }
    if(yearStart == yearEnd){
      for(var i=0;i<=monthEnd-monthStart;i++){
        var m = formatNum(monthEnd+1-i);
        str += '<option value="'+yearEnd+'-'+m+'">'+m+'-01'+'</option>';
      }
    }
    if(yearStart != yearEnd){
      for(var i=0;i<=monthEnd;i++){
        var m = formatNum(monthEnd+1-i);
        str += '<option value="'+yearStart+'-'+m+'">'+m+'月01日 - '+m+''+getLastDay(yearStart,m)+'日</option>';
      }
      for(var j=0;j<yearEnd-yearStart;j++){
        if(yearStart==yearEnd-j-1){
          for(var k=12;k>monthStart;k--){
            var m = formatNum(k);
            str += '<option value="'+yearStart+'-'+m+'">'+yearStart+''+m+'月</option>';
          }
        }else{
          for(var k=12;k>0;k--){
            var m = formatNum(k);
            console.log(m)
            str += '<option value="'+(yearEnd-j-1)+'-'+m+'">'+(yearEnd-j-1)+''+m+'月</option>';
          }
        }
      }
    }
    oSelect.innerHTML = str;
  }   
  function formatNum(num){
    return num<10?"0"+num:num;
  }
  //获取月份的最后一天为几号
  function getLastDay(year,month){
      var new_year = year;    //取当前的年份  
      var new_month = month++;//取下一个月的第一天,方便计算(最后一天不固定)  
      if(month>12) {          //如果当前大于12月,则年份转到下一年  
          new_month -=12;        //月份减  
          new_year++;            //年份增  
      }  
      var new_date = new Date(new_year,new_month,1);                //取当年当月中的第一天  
      return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月最后一天日期  
  }
  </script>
</body>
</html>

 

posted @ 2015-10-23 15:00  zhouzone  Views(279)  Comments(0Edit  收藏  举报