常用的日期处理方法

45 阅读1分钟

获取当前月的最后一天

/*整体思路:获取下一个月的第一天,然后-1天获取当月的最后一天*/

//获取当前的月份
var CurrentMonth = new Date().getMonth() + 1;

//得到下个月的日期
var NextMonthDate = new Date(new Date().setMonth(CurrentMonth));

//定义下个月一号的日期
//twoBitMonth保持两位数的月份
var twoBitMonth = getTwoBitMonth(NextMonthDate);
var NextMonthFirstDayDate = new Date(NextMonthDate.getFullYear() + "-" + twoBitMonth + "-01");

//通过setDate()获取当月最后一天的日期
var CurrentMonthLastDayDate = new Date(NextMonthFirstDayDate.setDate(NextMonthFirstDayDate.getDate() - 1));

//CurrentMonthLastDay即为当前月的最后一天
var CurrentMonthLastDay = CurrentMonthLastDayDate.getDate();

function getTwoBitMonth(date){
    return (date.getMonth() + 1) > 9 ? "" + (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
}

拿到某月的最后一天的值,可以处理很多有关日期需求

比如获取获取每个月中属于周一的日期

/*思路:循环当月的每一天,提取属于周一的日期*/
//定义一个数组容器,用来存入某月每周一的日期
var MondayDateList = [];
var month = getTwoBitMonth(new Date());
var CurrentYearMonthStr = new Date().getFullYear() + "-" + month;
for(var i=1; i <= CurrentMonthLastDay; i++){
   var day = i > 9 ? "" + i : "0" + i;
   var itemDate = CurrentYearMonthStr + "-" + day;
   if(new Date(itemDate).getDay == 1){
       MondayDateList.push(itemDate);
   }
}
//console.log(MondayDateList); MondayDateList里即包含了当前月中每周一的日期