Object-C NSCalendar获取当前时间

获取当前月份有多少天

    NSCalendar *calendar1 = nil;
    
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
        
        calendar1 = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    } else {
        
        calendar1 = [NSCalendar currentCalendar];
    }
    
    NSRange rangeMonth = [calendar1 rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    
    NSUInteger numberOfDaysInMonth = rangeMonth.length;
 
    NSLog(@"当前月份 %@ 天",@(numberOfDaysInMonth));  

获取当前年份和月份和天数

    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    unsigned unitFlags = NSCalendarUnitYear  |
                         NSCalendarUnitMonth |
                         NSCalendarUnitDay   |
                         NSCalendarUnitHour  |
                         NSCalendarUnitMinute|
                         NSCalendarUnitSecond|
                         NSCalendarUnitWeekday;
    
    NSDateComponents* components = [calendar components:unitFlags fromDate:[NSDate date]];
    NSInteger iCurYear = [components year]; //当前的年份
    NSInteger iCurMonth = [components month]; //当前的月份
    NSInteger iCurDay = [components day]; // 当前的号数

你可能感兴趣的:(Object-C NSCalendar获取当前时间)