//上個月 $(document).on('click', '#LastMonth', function () { SetLastAndFirstDate($('#fromdate').val(), -1); }) //本月 $(document).on('click', '#ThisMonth', function () { SetLastAndFirstDate($('#fromdate').val(), 0); }) //下個月 $(document).on('click', '#NextMonth', function () { SetLastAndFirstDate($('#fromdate').val(), +1); }) function SetLastAndFirstDate(nowday, tomonth) { var date = new Date(nowday); if (tomonth == 0) var date = new Date(); var firstDay = new Date(date.getFullYear(), date.getMonth() + (0 + tomonth), 1); var lastDay = new Date(date.getFullYear(), date.getMonth() + (1+tomonth), 0); $('#fromdate').val(formatDate(firstDay));//設定第一天 $('#todate').val(formatDate(lastDay));//設定最後一天 } function formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); }參考來源
Format JavaScript date as yyyy-mm-dd
取得當月第一天和最後一天