上月当天到本月当天

var now = new Date()  //当前日期
var year = now.getFullYear()   //当前年
var month = now.getMonth() + 1   //当前月
var day= now.getDate()   //当天
if (parseInt(month) < 10) {
    month = "0" + month
}
if (parseInt(day) < 10) {
    day = "0" + day
}

var dateObj = {}
dateObj.now = year + '' + month + '' + day
//这里当我们年月日添加的时候,中间一定也要写空的字符串,如果不写的话,极大可能这三个数会相加起来,下面的同理 !!!

if (parseInt(month) == 1) {
    dateObj.last = parseInt(year) - 1 + '12' + '01';
    this.startDay = dateObj.last
    this.endDay = dateObj.now
}
var preSize = new Date(year, parseInt(month) - 1, 0).getDate()
if (preSize < parseInt(day)) {
    dateObj.last = year + month + '01'
    this.startDay = dateObj.last
    this.endDay = dateObj.now
}
if (parseInt(month) < 10) {
    dateObj.last = year + '0' + parseInt(month) + '01'
    if (parseInt(month) == '01') {
        dateObj.last = year -1 + '12' + '01'
    }
    this.startDay = dateObj.last
    this.endDay = dateObj.now
} else {
    dateObj.last = year + '' + parseIng(month) + '01'
    this.startDay = dateObj.last
    this.endDay = dateObj.now
}
//我这个案例写的是当月的第一天到当天,如果需要的是上个月的今天到这个月的当天的话,只需要把 dateObj.last 后面加的‘01’改为day就可以实现

如果我们需要的是当天往前推几个月的,可以这么实现

var now = new Date()  //当前日期
var ago = null
if (now.getMonth() >= 8) {
    ago = new Date(now.getFullYear(), now.getMonth() - 8, now.getDate())
} else {
    ago = new Date(now.getFullYear() - 1, now.getMonth() + 4, now.getDate())
}
var year = ago .getFullYear()   //当前年
var month = ago .getMonth() + 1   //当前月
var day= ago .getDate()   //当天

//从这里开始,就跟上面的代码一样了

if (parseInt(month) < 10) {
    month = "0" + month
}
if (parseInt(day) < 10) {
    day = "0" + day
}

var dateObj = {}
dateObj.now = year + '' + month + '' + day

if (parseInt(month) == 1) {
    dateObj.last = parseInt(year) - 1 + '12' + '01';
    this.startDay = dateObj.last
    this.endDay = dateObj.now
}
var preSize = new Date(year, parseInt(month) - 1, 0).getDate()
if (preSize < parseInt(day)) {
    dateObj.last = year + month + '01'
    this.startDay = dateObj.last
    this.endDay = dateObj.now
}
if (parseInt(month) < 10) {
    dateObj.last = year + '0' + parseInt(month) + '01'
    if (parseInt(month) == '01') {
        dateObj.last = year -1 + '12' + '01'
    }
    this.startDay = dateObj.last
    this.endDay = dateObj.now
} else {
    dateObj.last = year + '' + parseIng(month) + '01'
    this.startDay = dateObj.last
    this.endDay = dateObj.now
}

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐