js实现日期选择器的两种方法(默认展示为最近一周)

方法一:
读取当前日期,再将day-7,判断day<=0针对不同月份的显示情况:

 let today = date.toISOString().split('T')[0];
    let oneWeekBefore = '';
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate() - 7;
    if(day <= 0 &&(month == 1||3||5||7||8||10||12)){
        day = 31+day;
        month --;
    }
    else if(day <= 0 &&(month == 2)){
        day = 28+day;
        month --;
    }
    else{
        day = 30+day;
        month --;
    };
    day = day > 9 ? day: '0' + day;  
    if(month == 0){
        oneWeekBefore = (year-1) + '-12-' + day;
    }
    else{
        month = month > 9 ? month: '0' + month;
        oneWeekBefore = year + '-' + month + '-' + day;
    };

方法二:
先读取当前日期,再读取七天前日期。

    let date = new Date();
    let today = date.toISOString().split('T')[0];
    let oneWeekBeforeDate = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
    let oneWeekBefore = oneWeekBeforeDate.toISOString().split('T')[0];

显然,第二种方法简便了很多。

你可能感兴趣的:(js实现日期选择器的两种方法(默认展示为最近一周))