计算2个日期之间的天数

  • 注意点:2个日期字符串的时间,不要全写' 00:00:00';
    如果全写' 00:00:00',在某些浏览器下会少算一天。
    // 返回值:一个数组,包含2个日期之间所有的天
    // startDateStr 和 endDateStr 格式:20171011
    getDaysBetweenArr: (startDateStr, endDateStr) => {
        var t1 = startDateStr.substr(0, 4) + '-' + (startDateStr.substr(4, 2)) + '-' + startDateStr.substr(6, 2) + ' 00:00:00'
        var t2 = endDateStr.substr(0, 4) + '-' + (endDateStr.substr(4, 2)) + '-' + endDateStr.substr(6, 2) + ' 23:00:00'
        var bd = new Date(t1.replace(/-/g, '/'))
        var be = new Date(t2.replace(/-/g, '/'))
        var bdTime = bd.getTime()
        var betime = be.getTime()
        var timediff = betime - bdTime
        var rangeDate = []
        for (var i = 0; i <= timediff; i += 86400000) {
            var ds = new Date(bdTime + i)
            var y = ds.getFullYear()
            var m = ds.getMonth() + 1 >= 10 ? ds.getMonth() + 1 : ('0' + (ds.getMonth() + 1))
            var d = ds.getDate() >= 10 ? ds.getDate() : ('0' + ds.getDate())
            rangeDate.push(y + '' + m + '' + d)
        }
        return rangeDate
    }

posted on 2018-03-13 19:32  cag2050  阅读(309)  评论(0编辑  收藏  举报

导航