所以我一直试图在一个int中找到这个月的最后一天,但我使用的代码总是认为最后一天是30
我使用的代码看起来像这样
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 :(得分:4)
试试这个简单的方法:
NSCalendar *cal = [NSCalendar currentCalendar];
NSRange rng = [cal rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = rng.length;
答案 1 :(得分: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);