views:

323

answers:

2

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

A: 

This is nothing natively supported.

You could roll your own function for this, working from the first day of the month

var currentDate = new Date();
var firstDayOfMonth = new Date( currentDate.getFullYear(), currentDate.getMonth(), 1 );

And then getting the weekday of that date:

var firstWeekday = firstDayOfMonth.getDay();

... which will give you a zero-based index, from 0-6, where 0 is Sunday.

David Hedlund
+1  A: 
function weekAndDay() {

    var date = new Date,
        days = ['Sunday','Monday','Tuesday','Wednesday',
                'Thursday','Friday','Saturday'],
        prefixes = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];

    return prefixes[0 | date.getDate() / 7] + ' ' + days[date.getDay()];

}

weekAndDay(); // => "Third Monday"

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

J-P
@J-P, this is perfect for me. Thanks for the solution. I have replaced fifth as last which is same as the repeat event (Monthly) in google calendar.
Prasad