使用daterangepicker获取月份的最后一天

时间:2018-07-26 06:04:08

标签: jquery

我想使用daterangepicker获取月份的最后一天。

这是我的剧本:

$('input[name="enddate"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    isInvalidDate: function( date ) {
        if( date.date() === getLastDayOfYearAndMonth(date.getFullYear(), date.getMonth()) ) {
            return false; 
        } else {
            return true;
        }
    },
    locale: {
        format: 'DD-MMM-YY'
    }
});

function getLastDayOfYearAndMonth(year, month) {
    return(new Date((new Date(year, month + 1, 1)) - 1)).getDate();
}

2 个答案:

答案 0 :(得分:0)

尝试使用月和年获取最后的日期:

console.log(getLastDayOfYearAndMonth(2018, 2));
function getLastDayOfYearAndMonth(year, month)
{
var d = new Date(year, month, 0);
var lastdate =d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
return lastdate;
}

修改后的答案:27-7-2018:

  

月+ 1表示如果选择2月,则将花费2月+ 1   = march,因此所需时间少于3月的第一天,因此将day参数设置为0意味着比该月的第一天少一天   上个月的最后一天

like explain here

jQuery(function($) {
  $('input[name="daterange"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    isInvalidDate: function( date ) {
   
var mydate = new Date(date);
var lastday = getLastDayOfYearAndMonth(mydate.getFullYear(), mydate.getMonth());
      if( date.date() === lastday) {
        return false; 
      } else {
        return true;
      }
    },
    locale: {
      format: 'DD-MMM-YY'
    }
  });
 
  
  //alert(getLastDayOfYearAndMonth('2018', '07'));
  function getLastDayOfYearAndMonth(year, month)
  {
    var d = new Date(year, month+1, 0);
    var lastdate =d.getDate();
    return lastdate;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link href="https://cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" rel="stylesheet"/>
<input type="text" name="daterange" />

答案 1 :(得分:0)

console.log(getLastDay(2018,7));

    function getLastDay(year,month) {        
    // GET THE MONTH AND YEAR OF THE SELECTED DATE.        
    var LastDay = new Date(year, month + 1, 0);
    // FINALLY, GET THE DAY.
    var weekday = new Array();
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";
    return weekday[LastDay.getDay()] +' (' + 
    LastDay.toDateString('dd/mon/yyyy') + ')';
}