当前位置:网站首页>Get last month, current time and next month

Get last month, current time and next month

2022-06-12 08:40:00 Pumpkin_ xiaoXuan

function getXmonthToday(type) {
    // type 0  It's the same day  -1  It was last month    1 It's next month 
    var now = new Date(); //  You can transfer the value mode  now = new Date(2019,2,30);  It's today 3 month 30 Number 
    var year = now.getFullYear();//getYear()+1900=getFullYear()
    var month = now.getMonth() + 1;//0-11 Express 1-12 month 
    var day = now.getDate(); //  Date of the day 
    if (parseInt(month) < 10) {
      month = "0" + month;
    }
    if (parseInt(day) < 10) {
      day = "0" + day;
    }
    now = year + '-' + month + '-' + day; //  If you take the date of the current month, you can directly  return  return 

    var preMonth = parseInt(month)  - 1;
    preMonth = preMonth < 10 ? '0' + preMonth : preMonth; //  Get the value of last month 
    var nextMonth = parseInt(month) + 1;
    nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth; //  Get the value of the next month 

    if (parseInt(month) == 1 && type == -1) {// If it is 1 month , Last month  , Take the last year's 12 month 
      return (parseInt(year) - 1) + '-12-' + day;
    } else if (parseInt(month) == 12 && type == 1) { //  If it is 12 month , Next month , Take the next year's 1 month 
      return (parseInt(year) + 1) + '-01-' + day;
    }

    var preSize  = new Date(year, parseInt(month) - 1, 0).getDate();// Total number of days in the previous month 
    var nextSize = new Date(year, parseInt(month)+ 1, 0).getDate();// Total number of days in the next month 
    console.log(preSize, nextSize)
    if (preSize < parseInt(day) && type == -1) {//  Take last month , If the total number of days in the previous month is less than today in this month , Take the last day of last month     
      return year + '-' + preMonth + '-' + preSize;
    } else if (nextSize < parseInt(day) && type == 1) { //  If the total number of days in the next month is less than today in this month , Take the last day of the month   
      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;
    }
  }

原网站

版权声明
本文为[Pumpkin_ xiaoXuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010547586423.html