SoFunction
Updated on 2025-04-08

IOS gets the number of days of the month of the specified year and month

Preface

This function is often needed in developing IOS. When the time interval of one month is limited to the first and last day, you need to know how many days there are in this month to know what the last day is, and you also need to know whether it is a leap year. It may be that February only has 28 days.

Without further ado, attach the code:

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:1]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:2]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:3]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:4]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:5]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:6]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:7]);
  NSLog(@"%ld",(long)[self howManyDaysInThisYear:2016 withMonth:8]);
}
#pragma mark - Get the number of days in a certain year and month- (NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
  if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
    return 31 ;
 
  if((month == 4) || (month == 6) || (month == 9) || (month == 11))
    return 30;
 
  if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3))
  {
    return 28;
  }
 
  if(year % 400 == 0)
    return 29;
 
  if(year % 100 == 0)
    return 28;
 
  return 29;
}

Summarize

The above is all the content of IOS obtaining the number of days of the month and day in a specified year and month. I hope the content of this article will be helpful to everyone in developing IOS.