views:

55

answers:

2

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 event. Is there a way in Javascript to create a Date object using just the year & week number? I googled it but did not come across any feasible solution.

Thanks for the help!

+2  A: 

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], // jan
        8:  [1, 8, 15, 22], // feb
        13: [1, 8, 15, 22, 29], // march
        17: [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]
    };

    return function(week, year) {
        if ( week > 52 || week < 01 ) { return false; }

        var d = new Date(),
            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 29 2010 18:51:28 GMT-0700 (PST) {}
Tue Sep 20 1983 18:51:28 GMT-0700 (PST) {}

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

Justin Johnson
Ah but there is something called week 53 also, see kennebec's post.
npup
+1  A: 

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= new Date(yw[0], 0, 1),
    day1= date1.getDay(),
    incr= (day1> 0 && day1<5)? -1: 1;
    if(yw[2]) weeks+= (+yw[2])-1;// optional day in week

    while(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
*/
kennebec