如何使用JS在一周中的任意日期时间获得一周的开始和结束?

时间:2016-07-26 12:19:30

标签: javascript datetime dayofweek

我有一个表示当前日期时间的ISO日期时间字符串:2016-07-26T11:56:59.792Z。如何获得[开始日期,结束日期>本周?

开始:2016-07-25T00:00:00.000Z 结束:2016-07-32T00:00:00.000Z

2 个答案:

答案 0 :(得分:0)

您可以使用答案herehere中提供的功能。



var year = 2016;
var week = 31;
document.write("first day: " + getDateOfISOWeek(week, year) + "<br>");


function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(+d);
    d.setHours(0,0,0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay()||7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(),0,1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
    // Return array of year and week number
    return [d.getFullYear(), weekNo];
}

function getDateOfISOWeek(w, y) {
    var simple = new Date(y, 0, 1 + (w - 1) * 7);
    var dow = simple.getDay();
    var ISOweekStart = simple;
    if (dow <= 4)
        ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
    else
        ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
    return ISOweekStart;
}
&#13;
&#13;
&#13;

因此您可以在此日期添加7天以获取最后日期。 (根据您需要的格式。)

答案 1 :(得分:0)

尝试这种方法。

var utcToday = '2016-07-26T11:56:59.792Z';

var start = startDate('2016-07-26T11:56:59.792Z');
console.log(start);
var end = endDate('2016-07-26T11:56:59.792Z');
console.log(end);

function startDate(dat){
var date = new Date(dat);  
var index = date.getUTCDay();
date.setUTCDate(date.getUTCDate()-(index-1));
date.setUTCHours('12');
date.setUTCMinutes('00');
date.setUTCSeconds('00');
date.setMilliseconds('000');
return date;
}
function endDate(dat){
var date = new Date(dat);  
var index = date.getUTCDay();
date.setUTCDate(date.getUTCDate()+(7-(index-1)));
date.setUTCHours('12');
date.setUTCMinutes('00');
date.setUTCSeconds('00');
date.setMilliseconds('000');
return date;
}