javascriptjquerydate

Get week of the month


How can i get the week number of month using javascript / jquery?

For ex.:

First Week: 5th July, 2010. / Week Number = First monday

Previous Week: 12th July, 2010. / Week Number = Second monday

Current Date: 19th July, 2010. / Week Number = Third Monday

Next week: 26th July, 2010. / Week Number = Last monday


Solution

  • function weekAndDay(date) {
        
        var days = ['Sunday','Monday','Tuesday','Wednesday',
                    'Thursday','Friday','Saturday'],
            prefixes = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];
    
        return prefixes[Math.floor(date.getDate() / 7)] + ' ' + days[date.getDay()];
    
    }
    
    console.log( weekAndDay(new Date(2010,7-1, 5)) ); // => "First Monday"
    console.log( weekAndDay(new Date(2010,7-1,12)) ); // => "Second Monday"
    console.log( weekAndDay(new Date(2010,7-1,19)) ); // => "Third Monday"
    console.log( weekAndDay(new Date(2010,7-1,26)) ); // => "Fourth Monday"
    console.log( weekAndDay(new Date()) );

    Adding the capability to have Last ... may take some more hacking...