0
点赞
收藏
分享

微信扫一扫

获取指定日期前一个月 并且转化时间戳

修炼之士 2022-03-12 阅读 67

function getXmonthToday(type,time) {
    // type 0 是当天 -1 是上个月   1是下个月
    var now = new Date(time); // 可以传值调式 now = new Date(2019,2,30); 今天是3月30号
    var year = now.getFullYear();//getYear()+1900=getFullYear()
    var month = now.getMonth() + 1;//0-11表示1-12月
    var day = now.getDate(); // 当天日期
    if (parseInt(month) < 10) {
      month = "0" + month;
    }
    if (parseInt(day) < 10) {
      day = "0" + day;
    }
    now = year + '-' + month + '-' + day; // 如果取当月日期可直接 return 返回

    var preMonth = parseInt(month)  - 1;
    preMonth = preMonth < 10 ? '0' + preMonth : preMonth; // 获取上个月的值
    var nextMonth = parseInt(month) + 1;
    nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth; // 获取下个月个月的值

    if (parseInt(month) == 1 && type == -1) {//如果是1月份,要上个月 ,则取上一年的12月份
      return (parseInt(year) - 1) + '-12-' + day;
    } else if (parseInt(month) == 12 && type == 1) { // 如果是12月,要下个月,取下一年的1月
      return (parseInt(year) + 1) + '-01-' + day;
    }

    var preSize  = new Date(year, parseInt(month) - 1, 0).getDate();//上月总天数
    var nextSize = new Date(year, parseInt(month)+ 1, 0).getDate();//下月总天数
    console.log(preSize, nextSize)
    if (preSize < parseInt(day) && type == -1) {// 取上个月,如果上个月总天数小于本月今天,取上个月最后一天    
      return year + '-' + preMonth + '-' + preSize;
    } else if (nextSize < parseInt(day) && type == 1) { // 如果下个月总天数小于本月今天,取下个月最后一天  
      return year + '-' + nextMonth + '-' + nextSize;
    }

    if (type == -1) {
      return year + '-' + preMonth + '-' + day;
    } else if (type == 1) {
      return year + '-' + nextMonth + '-' + day;
    }else if(type == 0){
      return now;
    }
  }
// 测试 

 let a = getXmonthToday(-1,"2022-3-10");//前一个月时间
 a=(new Date(a)).getTime();

举报

相关推荐

0 条评论