Getting the last day of a month

前端 未结 9 760
别跟我提以往
别跟我提以往 2020-12-08 00:24

How can I get the last day of the current month as an NSDate?

9条回答
  •  轮回少年
    2020-12-08 00:43

    Version from iOS 7

    just to get rid of the deprecations... with a minor addition to get the last second of the day.

        // current date
        NSDate *now = [NSDate new];
    
        // get last day of the current month
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        [calendar setTimeZone:[NSTimeZone systemTimeZone]];
    
        NSRange dayRange = [ calendar rangeOfUnit:NSCalendarUnitDay
                                           inUnit:NSCalendarUnitMonth
                                          forDate:now];
    
        NSInteger numberOfDaysInCurrentMonth = dayRange.length;
    
        NSDateComponents *comp = [calendar components:
                                  NSCalendarUnitYear |
                                  NSCalendarUnitMonth |
                                  NSCalendarUnitDay fromDate:now];
    
        comp.day = numberOfDaysInCurrentMonth;
        comp.hour = 24;
        comp.minute = 0;
        comp.second = 0;
    
        NSDate *endOfMonth = [calendar dateFromComponents:comp];
    

提交回复
热议问题