Get firstdate, lastdate of month?

后端 未结 8 1025
不思量自难忘°
不思量自难忘° 2021-02-01 21:29

I want to get firstdate、lastdate of month,I try

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.c         


        
8条回答
  •  一生所求
    2021-02-01 22:06

    You can get last date of month using :-

    NSDate currDate=[NSDate date];
    
    -(NSString *)getLastDateMonth:(NSDate *)currDate{
    
      NSCalendar *gregCalendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    
      NSDateComponents *components=[gregCalendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
      NSInteger month=[components month];
      NSInteger year=[components year];
    
      if (month==12) {
        [components setYear:year+1];
        [components setMonth:1];
      } else {
        [components setMonth:month+1];
      }
      [components setDay:1];
    
      NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
      [dateFormat setDateStyle:NSDateFormatterShortStyle];
      NSString *lastDateOfMonth = [dateFormat stringFromDate:(NSDate *)[[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:-86400]];
      dateFormat=nil;
      return lastDateOfMonth;
    }
    

提交回复
热议问题