How do you calculate the day of the year for a specific date in Objective-C?

一曲冷凌霜 提交于 2019-11-26 17:49:35
John Feminella

Try this:

NSCalendar *gregorian =
   [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear =
   [gregorian ordinalityOfUnit:NSDayCalendarUnit
     inUnit:NSYearCalendarUnit forDate:[NSDate date]];
[gregorian release];
return dayOfYear;

where date is the date you want to determine the day of the year for. The documentation on the NSCalendar.ordinalityOfUnit method is here.

So the solution I came up with is pretty neat and simple and not in any way complicated.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"D"];
NSUInteger dayOfYear = [[formatter stringFromDate:[NSDate date]] intValue];
[formatter release];
return dayOfYear;

The trick here which I spent so long time to figure out was to use the NSDateFormatter. The "D" is the flag for day of year.

Hope that this was helpful to you who have the same problem as I had.

Using ARC and replacing deprecated symbols, John Feminella's answer would look like this:

NSCalendar *greg    = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSUInteger dayOfYear= [greg ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:[NSDate date]];

Swift 4 variation:

let date = Date() // now
let calendar = Calendar(identifier: .gregorian)
let dayOfYear = calendar.ordinality(of: .day, in: .year, for: Date()) 

With the NSDate class. Use message timeIntervalSinceDate. It will return you a NSTimeInterval value (actually it's a double) that represents the seconds elapsed since the date you want. After that, it's easy to convert seconds-to-days.

If you truncate seconds/86400 will give you days.

Let's say you want days since January 1st 2010.

// current date/time
NSDate *now = [[NSData alloc] init]; 

// seconds elapsed since January 1st 2010 00:00:00 (GMT -4) until now
NSInteval interval = [now timeIntervalSinceDate: [NSDate dateWithString:@"2010-01-01 00:00:00 -0400"]];

// days since January 1st 2010 00:00:00 (GMT -4) until now
int days = (int)interval/86400;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!