ios当年的天数

时间:2012-09-25 13:45:39

标签: iphone ios nsdate

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

问候
的Pankaj

4 个答案:

答案 0 :(得分:7)

使用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

答案 1 :(得分:2)

使用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];

答案 2 :(得分:1)

根据data format reference,您可以使用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);

答案 3 :(得分:0)

使用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;