Home > Software design >  Create Date from string with week number in Javascript
Create Date from string with week number in Javascript

Time:12-02

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?

CodePudding user response:

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related