Get today's date several years ago in YY--MM--DD format, and get how many days before and after a certain date

I have encountered a problem recently, that is, I want to get the first few days of today, the next few days, the first few years of today, and the next few years.

Since I am not sure whether I want to get the dates before and after this year, I am not sure whether it is a few years or a few days. Then we will do two methods, one method is to calculate a certain year before and after this year, and the other method is to calculate the first few days of the year. Here is a brief introduction to these two methods
1.

function getLastYearYestdy(num){
    
     
      var date = new Date();
           var strYear = date.getFullYear() - num;    
           var strDay = date.getDate();    
           var strMonth = date.getMonth()+1;  
           if(strMonth<10)    
           {
    
        
              strMonth='0'+strMonth;    
           }  
           if(strDay<10)    
           {
    
        
              strDay='0'+strDay;    
           }  
           var datastr = strYear+'-'+strMonth+'-'+strDay;  
           return datastr;  
        }

The num parameter in this method represents the today's date several years ago you want. If you want the date several years later, just pass in a negative number for num .
2 days

 function getDateStr(days,AddDayCount) {
    
    
          var dd = new Date(days);
          dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
          var y = dd.getFullYear();
          var m = dd.getMonth()+1;//获取当前月份的日期
          var d = dd.getDate();
          return y+'-'+(m<10?'0'+m:m)+'-'+(d<10?'0'+d:d);
    }

The days parameter in this method represents the date you need to pass in, and the AddDayCount parameter represents the day before or after the date you want. If the AddDayCount parameter is '1', it means the day after this date, and if it is'-1', it means the day before this date.

Of course, if your needs have both years and days, you can change getLastYearYestdy(num) to the first parameter of the getDateStr method.

Guess you like

Origin blog.csdn.net/lbchenxy/article/details/99550076