testing
testing

Reputation: 20279

Calculate the number of weeks in a month including partial weeks

First I searched for an Xamarin.iOS equivalent for rangeOfUnit:inUnit:forDate:, but it seems there is none. I want to translate this code

NSRange rangeOfWeeks = [self.calendar rangeOfUnit:NSWeekCalendarUnit inUnit:NSMonthCalendarUnit forDate:firstOfMonth];

but there is no rangeOfUnit:inUnit:forDate in Xamarin.iOS. There are implementations like this

public static int Weeks(int year, int month)
{
    DayOfWeek wkstart = DayOfWeek.Monday;

    DateTime first = new DateTime(year, month, 1);
    int firstwkday = (int)first.DayOfWeek;
    int otherwkday = (int)wkstart;

    int offset = ((otherwkday + 7) - firstwkday) % 7;

    double weeks = (double)(DateTime.DaysInMonth(year, month) - offset) / 7d;

    return (int)Math.Ceiling(weeks);
} 

, but here partial weeks are not counted. I also think that you loss a part of the localization (no NSCalendar, ...), but that is another story.

How can I calculate the number of weeks in a month? If the month starts in the mid of a week it should count as full week. It should also counts as full week if the month ends in the mid of a week.

Upvotes: 0

Views: 1099

Answers (1)

SKall
SKall

Reputation: 5234

Looks like you are after the week number. If that is the case the below code gets it.

        nint era, year, weekOfYear, weekday;
        NSCalendar.CurrentCalendar.GetComponentsFromDateForWeekOfYear(out era, out year, out weekOfYear, out weekday, NSDate.Now);

        System.Diagnostics.Debug.WriteLine(weekOfYear);

        var weekOfMonth = NSCalendar.CurrentCalendar.GetComponentFromDate(NSCalendarUnit.WeekOfMonth, NSDate.Now);

        System.Diagnostics.Debug.WriteLine(weekOfMonth);

Today's week is #11 and it's the 2nd week of the month.

Upvotes: 3

Related Questions