I have a string like 2020-44 which contains year and number of the week in the year. Is it possible to create Date object from this string in some easy way? Javascripot is able to create dates from string like new Date('2020-12-24'). But I would like to use it with format 2020-44. Is it possible or not?
Asked
Active
Viewed 143 times
-1
-
3What date would it return? the first day of the chosen week? – evolutionxbox Dec 02 '21 at 14:21
-
@Camo, this may help you: https://stackoverflow.com/questions/8803151/how-to-get-first-date-and-last-date-of-the-week-from-week-number-and-year – Mani Dec 02 '21 at 14:30
-
How are weeks numbered? ISO week numbering starts from the Monday before the first Thursday of the year. Other systems use the first Sunday. What algorithm do you need? – RobG Dec 03 '21 at 00:38
-
Likely a duplicate of [*how to get a javascript date from a week number?*](https://stackoverflow.com/questions/17855064/how-to-get-a-javascript-date-from-a-week-number) – RobG Dec 03 '21 at 00:49
-
I dont know. It is the native PHP implementation which returns the number of the week. – Čamo Dec 03 '21 at 08:58
1 Answers
1
This will return the first day of the given week:
var dateString = "2020-44";
function getDateFromWeek(str) {
var y = str.split('-')[0]
var w = str.split('-')[1]
var d = (1 + (w - 1) * 7); // 1st of January + 7 days for each week
return new Date(y, 0, d);
}
console.log(getDateFromWeek(dateString));

Coder Gautam YT
- 1,044
- 7
- 20
-
2That works only where weeks are numbered from 1 January, making the first week of 2021 go from Fri 1 Jan to Thu 7 Jan, which isn't how weeks are typically numbered. ISO week numbering starts from Monday of the week with the first Thursday of the year, so 1 Jan 2021 was in ISO week 53 of 2020. – RobG Dec 02 '21 at 20:42