简体   繁体   中英

js Get first day of week by week number and year

Could you tell me what is the best way to get first day of week by week number and year?

I using this code from answer

function getDateOfWeek(week, y) {
   var d = new Date("Jan 01, "+y+" 01:00:00");
   var w = d.getTime() + 604800000 * (week-1);
   var n1 = new Date(w);
   var n2 = new Date(w + 518400000);
   return {
            dateFrom:n1,
            dateTo: n2
    }
}

getDateOfWeek(1,2017) returning dates: 01.01.2017, 08.01.2017

but need : 02.01.2017, 08.01.2017

getDateOfWeek(53,2016) returning dates: 30.12.2016, 05.01.2017

but need : 26.12.2016, 01.01.2017

Can you have some idea how to fix it?

Thanks.

You need to offset for day of the week

 function getDateOfWeek(week, y) { var d = new Date("Jan 01, " + y + " 01:00:00"); var dayMs = (24 * 60 * 60 * 1000); var offSetTimeStart = dayMs * (d.getDay() - 1); var w = d.getTime() + 604800000 * (week - 1) - offSetTimeStart; //reducing the offset here var n1 = new Date(w); var n2 = new Date(w + 518400000); return { dateFrom: n1, dateTo: n2 } } console.log(getDateOfWeek(1, 2017)); console.log(getDateOfWeek(53, 2016)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM