2014-06-29 2 views
0

Так я пытался найти в последний день месяца в междунар но код, я использую всегда думает, что в последний день 30Получение числа дней в NSDate в Objective-C?

Last Day is January

кода я использую выглядит так

NSDate *curDate = [NSDate date]; 
    NSCalendar* calendar = [NSCalendar currentCalendar]; 
    NSDateComponents* compsd = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components 

    // set last of month 
    [compsd setMonth:[compsd month]+1]; 
    [compsd setDay:0]; 
    NSDate *tDateMonth = [calendar dateFromComponents:compsd]; 
    //NSLog(@"%@", tDateMonth); 

    //[comps setMonth:[comps month]+1]; 
    //[comps setDay:0]; 
    // NSDate *tDateMonth = [cal dateFromComponents:comps]; 
    //NSLog(@"%@", tDateMonth); 
    //*/ 

    NSString *tDateString = [NSString stringWithFormat:@"%@", tDateMonth]; 
    NSString *dateNTime = [[tDateString componentsSeparatedByString:@"-"] objectAtIndex:2]; 
    int justDate = [[[dateNTime componentsSeparatedByString:@" "] objectAtIndex:0] intValue]; 
    NSLog(@"Last Day of %@ is %d", monthName, justDate); 

Что мне не хватает?

+0

возможного дубликата (HTTP://stackoverflow.com/questions/1179945/number-of-days-in-the-current-month-using-iphone-sdk) –

+1

Поскольку @Fry показал, что время исследования API-интерфейсов может сократить время кодирования. – zaph

+0

Что вам не хватает (между прочим) - это понимание того, как использовать NSDateFormatter. –

ответ

4

Попробуйте этот простой путь: [? Количество дней в текущем месяце с помощью iPhone SDK]

NSCalendar *cal = [NSCalendar currentCalendar]; 
NSRange rng = [cal rangeOfUnit:NSDayCalendarUnit 
         inUnit:NSMonthCalendarUnit 
         forDate:[NSDate date]]; 
NSUInteger numberOfDaysInMonth = rng.length; 
0

Я думаю, вы можете попробовать что-то вроде этого

NSDate *currentDate = [NSDate date]; 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:currentDate]; 

[components setMonth:[components month]+1]; 
[components setDay:0]; 
NSDate *theDate = [calendar dateFromComponents:components]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"d"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

NSString *dateString = [dateFormatter stringFromDate:theDate]; 
NSInteger dateInt = [dateString intValue]; 
NSLog(@"The int: %i", dateInt); 
Смежные вопросы