我想在 iphone 应用程序中检索给定月份的最后日期。谁能告诉我如何实现这一目标?我在 stackoverflow 上看到了一些解决方案,但他们只是给出了一个月的最后一天。
谢谢。
更新:
+(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