ios当年的天数

我想今天找到今天的天数。 例如,如果今天是2012年3月15日,我应该得到75(31 + 29 + 15)。 或者我们可以简单地说今天和今年1月1日之间的天数。 有人可以帮帮我吗?

问候
潘卡

使用NSCalendar的ordinalityOfUnit方法获取年份中的日期编号 – 在unUnit中指定NSDayCalendarUnit:NSYearCalendarUnit

NSCalendar *currentCalendar = [NSCalendar currentCalendar]; NSDate *today = [NSDate date]; NSInteger dc = [currentCalendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:today]; 

在2012年9月25日给出了269

使用NSDateComponents您可以收集NSDayCalendarUnit组件,该组件应指示一年中的当前日期。

以下内容应符合您的需求:

 //create calendar NSCalendar *calendar = [NSCalendar currentCalendar]; //set calendar time zone [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; //gather date components NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:[NSDate date]]; //gather time components NSInteger day = [components day]; 

根据数据格式参考 ,您可以使用D说明符来表示一年中的某一天。 如果您想要执行某些计算,日期格式化程序不是那么有用,但如果您只想显示一年中的某一天,这可能是最简单的方法。 代码看起来像:

 NSCalendar *cal = [NSCalendar currentCalendar]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setCalendar:cal]; [df setDateFormat:@"DDD"]; // D specifier used for day of year NSString *dayOfYearString = [df stringFromDate:someDate]; // you choose 'someDate' NSLog(@"The day is: %@", dayOfYearString); 

使用NSDateNSDateComponentsNSCalendar类,您可以非常轻松地计算上一年的最后一天与今天之间的天数(与计算当前年份的当前数字相同):

 // create your NSDate and NSCalendar objects NSDate *today = [NSDate date]; NSDate *referenceDate; NSCalendar *calendar = [NSCalendar currentCalendar]; // get today's date components NSDateComponents *components = [calendar components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:today]; // changing the date components to the 31nd of December of last year components.day = 31; components.month = 12; components.year--; // store these components in your date object referenceDate = [calendar dateFromComponents:components]; // get the number of days from that date until today components = [calendar components:NSDayCalendarUnit fromDate:referenceDate toDate:[NSDate date] options:0]; NSInteger days = components.day;