0

我将根据年计算天数。例如:如果这个月是九月,则根据当年计算天数(九月...十二月)。一月之后,它将根据明年计算。

我检索从当前月份到月底的月份数。

NSDate *curmonth=[NSDate date];
NSString *endmonthstr=@"2013-12-31";

NSDateFormatter *endmonthformatter=[[NSDateFormatter alloc]init];
[endmonthformatter setDateFormat:@"yyyy-MM-dd"];
NSDate *endmonth=[endmonthformatter dateFromString:endmonthstr];

NSInteger month = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit
                                                   fromDate: curmonth
                                                     toDate: endmonth
                                                    options: 0] month];

NSInteger monthplus=month+1;
NSInteger count=monthplus;

NSLog(@"%d",monthplus);

但是,我不知道如何比较这个并计算天数。

任何想法请帮助我

4

1 回答 1

0

要获取当年剩余的天数,您可以使用NSCalendar为您查找日期组件的差异。您可以指定不同的组件,但由于您需要日期,只需使用NSDayCalendarUnit.

NSCalendar *cal = [NSCalendar currentCalendar];

// GET CURRENT YEAR / MONTH / DAY
NSDate *now = [NSDate date];
NSDateComponents *nowComps = [cal components: NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate: now];

// COPY TODAY'S COMPONENTS, BUT CHANGE MONTH AND DAY
NSDateComponents *lastDayComps = [nowComps copy];
lastDayComps.month = 12;
lastDayComps.day = 31;

// GENERATE LAST DAY FROM COMPONENTS
NSDate *lastDay = [cal dateFromComponents: lastDayComps];

// CALCULATE DAYS BETWEEN DATES
NSDateComponents *components = [cal components: NSDayCalendarUnit fromDate: now toDate: lastDay options: 0];
NSInteger daysTilEndOfYear = components.day;
于 2013-08-31T07:33:42.880 回答