1

iPhoneアプリで特定の月の最終日を取得したい。どうすればこれを達成できるか誰にもわかりますか?stackoverflow でいくつかの解決策を見ましたが、月の最後の DAY を与えるだけです。

ありがとう。

アップデート:

    +(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

1 に答える 1

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];
    }
于 2012-05-20T06:59:04.403 に答える