2013-07-25 31 views
0

簡單的問題。我有一些骯髒的解決方案,但無法弄清楚一個乾淨,健壯的解決方案。問題是我有dayofyear(從SQL Server),我想將其轉換爲NSDate。詳細介紹:dayofyear到NSDate目標c

int dayofyear = 205 //I have this 

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

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

感謝

阿爾達

回答

4

獲得 「本年度的開始」:

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. 

添加205天:

int dayofyear = 205; 
NSDateComponents *comp = [[NSDateComponents alloc] init]; 
[comp setDay:dayofyear]; 
NSDate *newDate = [cal dateByAddingComponents:comp toDate:startOfYear options:0]; 
+0

+1用於獲取啓動日曆單元的日期。我不知道這種方法,謝謝! :-) –

+0

@LukasKukacka:是的,這很方便。使用'interval'參數你也會得到期間的結束,例如當天開始/結束日期。 –

+0

尚未實現但看起來很完美。謝謝! – ardavar