2011-07-21 26 views
1

我想增加我的NSDate。我有一個NSDictionary,我試圖增加我的NSDate內容。說我的NSDate是2011-07-11,我想增加它的NSDate內容。如何更改nsdictionary中的nsdate

{  
    ConditionDatenew = "2011-07-21 13:31:46 +0000"; 
    Yesterday = "2011-07-20 13:31:46 +0000"; 
    city = #; 
    condition = "Isolated Thunderstorms"; 
    country = #; 

    "day_of_week" = Sun; 
    high = 86; 
    icon = "chance_of_storm.gif"; 
    low = 68; 

    state = #; 
} 

我只是想獲得日期2011-07-22在我ConditionDatenew在未來字典循環。我怎麼才能得到它?

回答

1

創建一個新的日期對象,並替換字典中的舊值。日期是不可變的。

NSDate *newDate = [NSDate date]; 
[dictionary setObject:newDate forKey:@"ConditionDatenew"]; 

[NSDate date]將設置爲「now」。

添加一天最簡單的方法是添加24小時。只要DST永遠不是問題,這一方法就行得通,「通過增加一天」意味着「增加24小時」。如果你只使用UTC工作,那很好。

NSDate *newDate = [oldDate dateByAddingTimeInterval:24*60*60]; 

如果DST是一個問題(而且通常是),並以「增加一天」你的意思是「一個公曆日增」,那麼你需要使用最新組件,以確保你補充23,酌情24或25小時。

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
    [dateComponents setYear:2011]; 
    [dateComponents setMonth:11]; 
    [dateComponents setDay:6]; 
    [dateComponents setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]]; 
    NSDate *date = [calendar dateFromComponents:dateComponents]; 

    NSDateComponents *addComponents = [[NSDateComponents alloc] init]; 
    [addComponents setDay:1]; 
    [addComponents setTimeZone:[NSTimeZone localTimeZone]]; 
    NSDate *newDate = [calendar dateByAddingComponents:addComponents toDate:date options:0]; 

    NSLog(@"oldDate=%@", [date descriptionWithLocale:[NSLocale currentLocale]]); 
    NSLog(@"+24=%@", [[date dateByAddingTimeInterval:24*60*60] descriptionWithLocale:[NSLocale currentLocale]]); 
    NSLog(@"newDate=%@", [newDate descriptionWithLocale:[NSLocale currentLocale]]); 
    [calendar release]; 
    [dateComponents release]; 
    [addComponents release]; 

輸出:

oldDate=Sunday, November 6, 2011 12:00:00 AM Eastern Daylight Time 
+24=Sunday, November 6, 2011 11:00:00 PM Eastern Standard Time 
newDate=Monday, November 7, 2011 12:00:00 AM Eastern Standard Time 

如果你不計較時間,並有超過你將它設置爲控制,一招是設置時間到了中午。那樣增加24小時將總是在正確的一天。我通常不建議這樣做,因爲如果你忘記和創建一個午夜時間的日期,它會失敗。將所有日增量代碼放在一個地方並修復DST問題比確保所有日期創建代碼始終正確更容易。所以我建議習慣日期組件。

+0

如何建立新的對象......我的字典對象conditiondate是沒有得到增量..... – new

+0

當你說「增量」你的意思「設置爲現在「或」添加一些東西?「 '[NSDate date]'會給你「現在」。 –

+0

我的意思是添加一些東西..我的日子應該增加1天,每次循環運行...我解析我的日期在字典中...... – new

0

試試這個:

NSDate *newDate = [NSDate date]; 
[dictionary setValue:newDate forKey:@"ConditionDatenew"]; 
+0

沒有理由在這裏使用'-description'。你可以直接在'NSDictionary'中存儲'NSDate',這樣更靈活。 –