Js获取时间 年月日 封装

// 获取日期
function getBeforeDate(n){
    var date = new Date() ;
    var year,month,day ;
    date.setDate(date.getDate()-n);
    year = date.getFullYear();
    month = date.getMonth()+1;
    day = date.getDate() ;
    s =  ( month < 10 ? ( '0' + month ) : month ) + '-' + ( day < 10 ? ( '0' + day ) : day) ;
    return s ;
}  
console.log(getBeforeDate(0));//昨天的日期   12-12

// 获取月份
function getBeforeMonth(n){
    var date = new Date() ;
    var year,month,day ;
    date.setDate(date.getMonth()+1-n);   
    month = date.getDate()    // console.log(month);   
    s = month+'月';
    // s =  ( month < 10 ? ( '0' + month ) : month +'月') ;
    return s;
}  
console.log(getBeforeMonth(0));    //12月
// console.log(getBeforeMonth(5));

// 获取年月
function getBeforeYM(n){
    var date = new Date() ;
    var year,month,day ;
    date.setDate(date.getMonth()+1-n);
    year = date.getFullYear();
    month = date.getDate(); 
    s =  year+""+( month < 10 ? ( '0' + month ) : month )  ;
    return s ;
}  
console.log(getBeforeYM(1));//201811 

猜你喜欢

转载自blog.csdn.net/weixin_42481234/article/details/84969105