Question

The common question on stackoverflow is how to get the Day of Year from a date but how to you get the date from the Day of Year?

I'm using the following code to generate the Day of Year but how to I do the converse?

// Calculate Day of the Year
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
    setDayOfYear = dayOfYear;
    return setDayOfYear;
Was it helpful?

Solution

Assuming you know the year you want and the actual time of the date doesn't matter and you have the correct locale and time zones set up, you can just convert the day of the year and year from components back into a date. Again, you may need to decide what your application needs to do about the time component and you have to make sure that the day and year actually make sense for the calendar, but assuming the gregorian calendar you listed in your example, and the 200th day of 2013 (19 July, 2013), you could so something like this:

NSDateComponents* components = [[NSDateComponents alloc] init];
[components setDay:200];
[components setYear:2013];
NSDate* july19_2013 = [gregorian dateFromComponents:components];

If I were to run this, I'd get a date that's 19 July, 2013 @ 07:00 since my current locale is in a time zone equiv of America/Los_Angeles and I didn't configure the calendar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top