需求:根据当天日期,获得所在周的所有日期,比如今天(2018-01-21)那么这一周的日期是:
    [‘2018-01-15’,…’2018-01-21’],要支持跨年,跨月。
    注:星期一为一周的开始,星期天为结束
    方法一:

    const dateOfToday = Date.now() const dayOfToday = (new Date().getDay() + 7 - 1) % 7 const daysOfThisWeek = Array.from(new Array(7)) .map((_, i) => { const date = new Date(dateOfToday + (i - dayOfToday) 1000 60 60 24)

    return date.getFullYear() +

    1. '-' +
    2. String(date.getMonth() + 1).padStart(2, '0') +
    3. '-' +
    4. String(date.getDate()).padStart(2, '0')

    })

    方法二(推荐):

    function getDates(currentTime) {//JS获取当前周从星期一到星期天的日期

    var currentDate = new Date(currentTime)

    var timesStamp = currentDate.getTime();

    var currenDay = currentDate.getDay();

    var dates = [];

    for (var i = 0; i < 7; i++) {

    1. dates.push(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)).toLocaleDateString().replace(/\//g, '-'));

    }

    return dates

    }

    方法三:

    function getWeekDay(dateString) {

    let dateStringReg = /^\d{4}[/-]\d{1,2}[/-]\d{1,2}$/;

    if (dateString.match(dateStringReg)) {

    1. let presentDate = new Date(dateString),
    2. today = presentDate.getDay() !== 0 ? presentDate.getDay() : 7;
    3. return Array.from(new Array(7), function(val, index) {
    4. return formatDate(new Date(presentDate.getTime() - (today - index-1) * 24 * 60 * 60 * 1000));
    5. });

    } else {

    1. throw new Error('dateString should be like "yyyy-mm-dd" or "yyyy/mm/dd"');

    }

    function formatDate(date) {

    1. return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();

    }

    }

    console.log(getWeekDay(‘2018-1-8’));

    文章来源:https://segmentfault.com/q/1010000012923451