How to retrive Last date of month give month as parameter in iphone

青春壹個敷衍的年華 提交于 2019-12-08 07:26:46

问题


I want to retrieve the last date of given month in iphone app. Can anybody tell how can I achieve this? I saw some solution on stackoverflow , but they just giving last DAY of month.

Thanks.

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;

}

If I use this code it showing me wrong output in console as follows

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

回答1:


You can do that by using this function :-

 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];
    }


来源:https://stackoverflow.com/questions/10671372/how-to-retrive-last-date-of-month-give-month-as-parameter-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!