2012-08-01 38 views
0

如何從一年中的某天獲取日期? 例如,如果我將日期設置爲「1」,那麼日期應該是「1月1日」如何從iPhone中的一天中獲取日期?

如何在iPhone中獲得?我已經在javascript中找到了答案,但我想知道如何在Objective中實現相同的目標?從崗位

回答

2

我想這段代碼會爲你工作: 我創建了一個樣本函數,其中一個文本框給出了多少天添加的輸入值。還有一個按鈕來計算最後一天。這是按鈕事件邏輯。

NSDateComponents *dateComponent = [[NSDateComponents alloc] init]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    [formatter setDateFormat:@"yyyy-mm-dd"]; 

    NSDate *newDate = [formatter dateFromString:@"2012-01-01"]; 

    // add days to current date 
    dateComponent.day = [dayTextField.text intValue]; 

    // get a new date by adding components 
    newDate = [[NSCalendar currentCalendar] dateByAddingComponents: dateComponent toDate:newDate options:0]; 

    [finalDate setText:[NSString stringWithFormat:@"%@", newDate]]; 

這裏dayTextField.text是表示要計算多少天的文本。 (例如125天),finalDate是顯示最終生成日期的標籤(意思是自2012年1月1日起125天后的日期)。

此代碼的優點是,您可以隨時更改開始日期參數。例如,對於其他要求,我需要從「1999年5月31日」算起我的日子,然後我將在一行中輕鬆更改它,並且相同的代碼將起作用。

享受編碼:)

1
NSCalendar *gregorian = 
    [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSUInteger dayOfYear = 
    [gregorian ordinalityOfUnit:NSDayCalendarUnit 
    inUnit:NSYearCalendarUnit forDate:[NSDate date]]; 
[gregorian release]; 
return dayOfYear; 

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

+0

如果你發現另一SO質疑這是相同的,我們該做的是將此問題作爲一個重複。 :) – Almo 2012-08-01 13:46:11

+0

這個答案與問題所要求的完全相反。 *週期完成* – WDUK 2012-11-27 16:08:53

相關問題