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

早过忘川 提交于 2019-11-26 05:36:32

问题


This is something I found myself spending hours to figure out and therefore want to share with you.

The question was: How do I determine the day of the year for a specific date?

e.g. January 15 is the 15th day and December 31 is the 365th day when it\'s not leap year.


回答1:


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.




回答2:


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.




回答3:


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



回答4:


Swift 4 variation:

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



回答5:


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;


来源:https://stackoverflow.com/questions/2080927/how-do-you-calculate-the-day-of-the-year-for-a-specific-date-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!