0

How would I get the week number in the month of a Date?

I can retrieve the week number in a year w/ getWeekOfTheYear (d:Date) but a calculation based around that will prove difficult - any help is greatly appreciated

Returned value I would expect would typically range from [0 - 4]

user601935
  • 133
  • 1
  • 1
  • 7
  • I found a PHP snippet: function week_number( $date = 'today' ) { return ceil( date( 'j', strtotime( $date ) ) / 7 ); } could this be replicated? – user601935 Mar 25 '16 at 14:02
  • Try to get the week number in a year of date you need to calculate week number in a month (`m1`), then get the week number of first day of desired month (`m2`). Then substract m2 from m1. You will get the zero-based week number in month. – Vasyl Moskalov Mar 25 '16 at 14:02
  • Actually all you have to do is take a day (1-31) and divide it by 7. Like `Math.floor(yourDateInstance.date/7);` will give the week (0-4) or use Math.ceil for week (1-5) – michaPau Mar 29 '16 at 09:46

2 Answers2

1

Take a look at this aproach:

Get current calendar week

Use the function week_num to get the week number passing a date object as you wanted.

Community
  • 1
  • 1
0

You have to account for months starting in the middle of the week, where e.g. the 1st is a Thursday.

Get the week day number of the months 1st day minus one. Add that to your current date, divide by 7, floor it, add one to the result: That's the months week (zero-based) of that day.

// be carful to provide month zero-based like AS need it to be
private function monthWeekOfDay(year:int, month:int, day:int, weekStartsOnMonday:Boolean = false):int
{
    var firstDay:int = new Date(year, month, 1).getDay();
    if (weekStartsOnMonday)
        firstDay = (firstDay + 6) % 7;
    firstDay--;

    return Math.floor((new Date(year, month, day).getDate() + firstDay) / 7);
}
geesys
  • 11
  • 3