Reputation: 11389
All:
Could anyone give me a simple way to calculate what are the beginning UTC time and ending UTC time based on the week number? For eaxample, now it is week 29 which starts from 2016-07-18(Monday) to 2016-07-24(Sunday). In this case, I need to know what starting/ending days are and what their UTC time
Thanks
Upvotes: 0
Views: 1132
Reputation: 3579
Using a combination of answers from "javascript calculate date from week number" and "JavaScript - get the first day of the week from current date" while using UTC variants of the get/set functions, you can arrive at:
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());
Upvotes: 2
Reputation: 3669
Simply rely on Janury 1st.
Example:
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)
Upvotes: 1