How Many Days Are In The Current Month

If you ever need to determine how many days are in the current month, here are a few lines of code to get you there.

Calling the rangeOfUnit method in the NSCalendar object, you specify both a small and large calendar units. In this case, a day unit within a month unit. With that information in hand, check the length of the returned range to determine how many days in the month:

// Use today's date
NSDate *today = [NSDate date];
 
// With a calendar object, request the day unit of the month unit
NSRange dayRange = [[NSCalendar currentCalendar] 
  rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today];
 
NSLog(@"There are %d days in the current month.", dayRange.length);

I ran this example on April 4th, 2012, here is the output:

2012-04-04 21:42:33.816 Sandbox[4862:f803] There are 30 days in the current month.

If you know of another way to get the same information, feel free to post a code example.

    • This is in the h file:

      Calendar Units

      Specify calendrical units such as day and month.

      enum {
      ….
      NSMonthCalendarUnit = kCFCalendarUnitMonth,
      ….
      NSWeekdayCalendarUnit = kCFCalendarUnitWeekday,
      ….
      };
      typedef NSUInteger NSCalendarUnit;


      if you swap NSMonthCalendarUnit for NSWeekdayCalendarUnit, maybe that would help.

Comments are closed.