get NSDate from the day of the year
I have a the day of the year for example 346. I want to get NSDate to n开发者_如何学运维ow what month and day it means.
Your steps here:
- Instantiate calendar
- Build a date with 1st Jan. of the year
- Add the number of days - 1 and build a date with that
- Get the components you are interested in
Watch out if the date you get is 0- or 1-based.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:theYear];
[comps setMonth:1];
[comps setDay:1];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
[comps setDay:theDay-1];
NSDate *finalDate = [gregorian dateByAddingComponents:compsToAdd date options:0];
[compsToAdd release]
NSDateComponents *interestingComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:finalDate];
NSInteger day = [interestingComponents day];
NSInteger month = [interestingComponents month];
[gregorian release];
See the -dateByAddingComponents:toDate:options:
method of NSCalendar
.
精彩评论