Search code examples
javascriptdatedatejsisodate

Trying to return javascript date based on "week 4 2013" using date.js


I'm trying to figure out the date from a week number (date would be week starting on [date]).

It works on the home page of the date.js website (see image), but I can't get it to work.

date.js website works

I'm using var date = Date.parse('week 5 2013');, but that always returns today's date.

What am I doing wrong?

Thanks, Angus


Solution

  • If you are not wedded to date.js it is pretty simple to calculate the nth week of a year-

    The first week of a year begins on the first Monday of that year,

    if the first week includes a thursday.

    Otherwise the first week of a year (like 2013)

    begins on the last Monday of the previous year.

    function nthWeek(y, n){
        if(y== undefined) y= new Date().getFullYear();
        var start= new Date(y, 0, 1);
        if(start.getDay()>4) start.setDate(start.getDate()+7);
        while(start.getDay()!= 1) start.setDate(start.getDate()-1);
        if(!n || n== 1) return start;
        start.setDate(start.getDate()+((n-1)*7));
        return start;
    }
    
    
    
    
    var s='week 4 2013';
    var m=s.match(/(\d+)/g);
    
    alert(nthWeek(m[1],m[0]));
    

    /* returned value: (Date) Mon Jan 21 2013 00:00:00 */