js中对时间的处理

1.计算当前月最大天数

        DaysInMonth : function (year, month) {
            if (month == 1) {
                if (year % 4 == 0 && year % 100 != 0)
                    return 29;
                else
                    return 28;
            } else if ((month <= 6 && month % 2 == 0) || (month > 6 && month % 2 == 1))
                return 31;
            else
                return 30;
        },

2.增加整月数

        //增加日期 number 月数  date 开始日期
        DateAdd: function (number, date) {
            var me = this;
            var y = date.getFullYear();
            var m = date.getMonth();
            var nextY = y;
            var nextM = m;
            //如果当前月+增加的月>11 这里之所以用11是因为 js的月份从0开始
            if ((m + number) > 11) {
                nextY = y + 1;
                nextM = parseInt(m + number) - 12;
            } else {
                nextM = date.getMonth() + number
            }
            var daysInNextMonth = me.DaysInMonth(nextY, nextM);
            var day = date.getDate()-1;
            if (day > daysInNextMonth) {
                day = daysInNextMonth;
            }
            return new Date(nextY, nextM, day);
        },

3.日期加上天数得到新的日期

//dateTemp 需要参加计算的日期,days要添加的天数,返回新的日期,日期格式:YYYY-MM-DD  
        getNewDay: function (dateTemp, days) {
            var dateTemp = dateTemp.split("-");
            var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]); //转换为MM-DD-YYYY格式    
            var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);
            var rDate = new Date(millSeconds);
            var year = rDate.getFullYear();
            var month = rDate.getMonth() + 1;
            if (month < 10) {
                month = "0" + month;
            }
            var date = rDate.getDate();
            if (date < 10) {
                date = "0" + date;
            }
            return (year + "-" + month + "-" + date);
        },
posted @ 2021-12-02 15:14  86岁带病上场  阅读(76)  评论(0)    收藏  举报