在Javascript中根据周数获取日期的简单方法

时间:2016-07-21 16:40:24

标签: javascript date

所有

有人能给我一个简单的方法来计算基于周数的UTC开始时间和结束UTC时间是什么时候?例如,现在是第29周,从2016-07-18(星期一)到2016-07-24(星期日)。在这种情况下,我需要知道什么是开始/结束日期以及它们的UTC时间

由于

2 个答案:

答案 0 :(得分:2)

使用" javascript calculate date from week number"的答案组合和" JavaScript - get the first day of the week from current date"使用get / set函数的UTC变体时,您可以到达:

function getDateOfISOWeek(w, y) {
    var simple = new Date(Date.UTC(y, 0, 1 + (w - 1) * 7));
    var dow = simple.getUTCDay();
    var ISOweekStart = simple;
    if (dow <= 4)
        ISOweekStart.setUTCDate(simple.getUTCDate() - simple.getUTCDay() + 1);
    else
        ISOweekStart.setUTCDate(simple.getUTCDate() + 8 - simple.getUTCDay());
    return ISOweekStart;
}

function getEndOfISOWeek(d) {
        var endOfISOWeek = new Date(d.getTime());
    endOfISOWeek.setUTCDate(endOfISOWeek.getUTCDate() + 6); // six days
    endOfISOWeek.setUTCHours(23);
    endOfISOWeek.setUTCMinutes(59);
    endOfISOWeek.setUTCSeconds(59);
    return endOfISOWeek;
}

var startOfWeek = getDateOfISOWeek(29,2016);
var endOfWeek = getEndOfISOWeek(startOfWeek);

console.log(startOfWeek.toUTCString(), endOfWeek.toUTCString());

JSFiddle of above code

答案 1 :(得分:1)

只需依靠Janury 1st。

示例:

function getBounds(weekNum, year) { // getBounds(weekNum [, year])
    var week = 604800000; // 1000 * 60 * 60 * 24 * 7
    year || (year = (new Date()).getFullYear()); // Defaults to current year.
    var d = Date.parse(year+'-1-1');
    var wEnd = d + week * weekNum; // We count weeks from 1.
    return [wEnd - week, wEnd];
};

console.log(getBounds(29)); // [ 1468537200000, 1469142000000 ] (during 2016)
console.log(getBounds(29, 2016)); // [ 1468537200000, 1469142000000 ] (forever)