我将根据年份计算天数。例如:如果这个月是9月,那么根据当前年度计算天数(9月到12月)。在1月之后,它将基于计算明年。
我检索从当月到月底的月数。
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);
但是,我不知道如何比较这个并计算天数。
任何想法请帮助我
答案 0 :(得分: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;