简体   繁体   中英

convert a week number and year to a date object in Javascript

I am very new to web development and I am currently working on a dashboard my data comes from a MySql database. I would like to convert a week number and year to an actual date object in the frontend using javascript. This is my first try, which i stumbled while researching I believe that this function assumes the first day of the week of the current year is Monday(1):

function getDateOfWeek(w, y) {
   var d = 1 + (w - 1) * 7;
 
   return new Date(y, 0, d);
 }

But the idea that the first day of the week is always Monday is desirable what if otherwise? So upon more research, I modified the code to look like this:

let currentDate = new Date()
let currentYear = currentDate.getFullYear()
let firstOfJan = new Date(currentYear, 0, 1).getDay();

function getDateOfWeek(w, y) {
   var d = firstOfJan + (w - firstOfJan) * 7;
 
   return new Date(y, 0, d);
 }

Please I am not sure if this solves the problem 100 percent. Is there a downside to the function above? or does it cover it? or I am missing something? Thank you for your time

There are various schemes for calculating week number. ISO 8601 uses Monday before the first Thursday of the year as the start of the first week. So the last few days of a year may be in the first week of the following year, and the first few days may be in the last week of the previous year. There might be 52 or 53 weeks in a year. There are other schemes. Which one do you want to use?

The following converts an ISO week into a Date. It doesn't validate the input, so you'll need to add that.

 // Convert week in format yyyyWww (eg 2022W05) to Date function isoWeekToDate(isoWeek) { let [y, w] = isoWeek.split(/w/i); // Get date for 4th of January for year let d = new Date(y, 0, 4); // Get previous Monday, add 7 days for each week after first d.setDate(d.getDate() - (d.getDay() || 7) + 1 + (w - 1) * 7); return d; } // Tests ['2010W01', '2011W01', '2012W01', '2013W01', '2014W01', '2015W01', '2016W01', '2017W01', '2018W01', '2019W01', '2020W01'].forEach(s => console.log(isoWeekToDate(s).toDateString()) );

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