2012-05-20 59 views
1

我想檢索iphone應用程序中給定月份的最後日期。任何人都可以告訴我如何實現這一目標?我在stackoverflow上看到了一些解決方案,但他們只是給了最後一個月的一天。如何檢索月最後一個日期給月作爲參數在iphone

謝謝。

UPDATE:

+(NSString*)getLastDateOfMonth:(NSString *)monthYearString { 

    //NSString *inputDate = [NSString stringWithFormat:@"%@ %@",@"01",monthYearString]; 
    NSString *inputDate = [NSString stringWithFormat:@"%@ %@",@"01",@"May 2012"]; 
    NSLog(@"Input date:- %@",inputDate); 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setDateFormat:@"dd MMM yyyy"]; 
    NSDate *date = [dateFormatter dateFromString:inputDate]; 

    NSCalendar *gregCalendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 

    NSDateComponents *components=[gregCalendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date]; 
    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]; 

    NSDate *lastDate = [[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:0]; 

    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc]init]; 
    [outputFormatter setDateFormat:@"MM/dd/yyyy"]; 
    NSString *lastDateOfMonth = [outputFormatter stringFromDate:lastDate]; 

    return lastDateOfMonth; 

} 

如果我用這個代碼,它顯示我在控制檯輸出錯誤如下

Input date:- 01 May 2012 
LAst DAte in Month:- 06/01/2012 

回答

4

你可以通過使用此功能: -

NSDate currDate=[NSDate date]; 

NSDate *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]; 

    return [[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:0]; 
    } 
+0

如果我使用上面的函數,我會得到錯誤的日期。我調用這個函數就像這個NSLog(@「LAst DAte in Month: - %@」,[Common getLastDateOfMonth:[NSDate date]]);我的控制檯輸出爲「LAst DAte in Month: - 2012-05-30 18 :30:00 +0000「 – iOSAppDev

+0

從回報中刪除-86400,只需添加0 –

+0

謝謝。添加0完美工作。 – iOSAppDev

相關問題