1

I want to know the shortest way to calculate week no of the month. Please see below.

This month is May 2014

Mon     Tue      Web     Thurs     Fri       Sat      Sun
                           1        2         3        4    <======= Week 1
5        6        7        8        9         10       11   <======= Week 2
12       13       14       15       16        17       18   <======= Week 3
19       20       21       22       23        24       25   <======= Week 4
26       27       28       29       30        31            <======= Week 5
zanhtet
  • 2,040
  • 7
  • 33
  • 58
  • 1
    Also see this: http://stackoverflow.com/questions/5974798/how-to-find-week-of-month-for-calendar-which-starts-from-monday – gen_Eric May 15 '14 at 14:45
  • I think `Math.floor((6 + new Date().getDay()) / 7)` should also do the trick. – Hampus May 15 '14 at 14:55

2 Answers2

2

I think this function should do the work.

        function getWeekNo(date) {

            var day = date.getDate()

            //get weekend date
            day += (date.getDay() == 0 ? 0 : 7 - date.getDay());

            return Math.ceil(parseFloat(day) / 7);
        }

        alert(getWeekNo(new Date(2015, 2, 31)));

When I tested, it turns out giving correct results for:

  1. Months where first day of the month is Monday, Tuesday or Sunday
  2. Months that span over four, five and six weeks
Pyae Phyo Aung
  • 828
  • 2
  • 10
  • 29
-1

Math.ceil(new Date().getDay() / 7)

Reece
  • 396
  • 3
  • 11
  • any reason for the downvote? this seems to achieve the exact desired functionality for me. – Reece May 15 '14 at 14:55
  • No. May 1st returns 0, May 14th returns 2 instead of 3 – Aserre May 15 '14 at 14:57
  • Even if you add 1. September 1st is a monday, thus September 7th is a sunday and is in week 1. With your function, it would be in week 2. With ceil, may 5th would be in week 1. – Aserre May 15 '14 at 15:01
  • Ah now I see what the OP meant by week number of the month; calendar weeks – Reece May 15 '14 at 15:03