Skip to content Skip to sidebar Skip to footer

Is There A Way In Javascript To Create A Date Object Using Year & Iso Week Number?

I am trying to create a google annotated timeline viz. For that I need to input the date of the event. The only information I have is the year & the ISO week number for the eve

Solution 1:

ISO weeks start on Monday

If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year

Date.weekofYear= function(s){
    var yw= s.split(/\D+0?/),
    weeks= 7*yw[1]-7,
    date1= newDate(yw[0], 0, 1),
    day1= date1.getDay(),
    incr= (day1> 0 && day1<5)? -1: 1;
    if(yw[2]) weeks+= (+yw[2])-1;// optional day in weekwhile(date1.getDay()!= 1){
        date1.setDate(date1.getDate()+incr);
    }
    date1.setDate(date1.getDate()+weeks);
    return date1;
}

Date.weekofYear('2010-20').toLocaleDateString()
// (use UTC methods to start the weeks on Greenwich instead of local time)/*  returned value: (String)
Monday, May 17, 2010
*/

Solution 2:

Interesting problem. Here's my solution:

var week2date = (function() {
    var weekToDate = {
        // last week number in the month: [first date of each week]4:  [4, 11, 18, 25], // jan8:  [1, 8, 15, 22], // feb13: [1, 8, 15, 22, 29], // march17: [5, 12, 19, 26], // etc ...22: [3, 10, 17, 24, 31],
        26: [7, 14, 21, 28],
        30: [5, 12, 19, 26],
        35: [2, 9, 16, 23, 30],
        39: [6, 13, 20, 27],
        43: [4, 11, 18, 25],
        48: [1, 8, 15, 22, 29],
        52: [6, 13, 20, 27]
    };

    returnfunction(week, year) {
        if ( week > 52 || week < 01 ) { returnfalse; }

        var d = newDate(),
            lastw = 0,
            month = 0;

        for ( var w in weekToDate ) {
            if ( !weekToDate.hasOwnProperty(w) ) { continue; }
            if ( w >= week ) {
                break;
            }
            lastw = w;
            ++month;
        }

        d.setFullYear(year || d.getFullYear(), month, weekToDate[w][week - lastw - 1]);
        return d;
    }
})();

Use:

console.log(week2date(13));
console.log(week2date(38, 1983));

Output:

Mon Mar 29201018:51:28 GMT-0700 (PST) {}
Tue Sep 20198318:51:28 GMT-0700 (PST) {}

I used this table on wikipedia to get the date information.

Solution 3:

I second Mr.s @kennebec's answer, but since I can't yet comment, I would want to add that the ISO notation for the week of year representation is yyyy-Www. As an example: 2000-W01. Note the week padding as well.

Post a Comment for "Is There A Way In Javascript To Create A Date Object Using Year & Iso Week Number?"