Question

Simple question. I have some dirty solutions but couldn't figure out a clean, robust one. The problem is I have the dayofyear (from SQL Server), I want to convert it to NSDate. In detail:

int dayofyear = 205  //I have this 

NSDate* date =  ??something by adding dayofyear to 1/1/currentyear(2013)??

//must have :  date = 07/25/2013

Thanks

arda

Was it helpful?

Solution

Get "start of current year":

NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfYear;
[cal rangeOfUnit:NSYearCalendarUnit startDate:&startOfYear interval:NULL
         forDate:now];
// startOfYear represents now the start of the current year.

Add 205 days:

int dayofyear = 205;
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:dayofyear];
NSDate *newDate = [cal dateByAddingComponents:comp toDate:startOfYear options:0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top