2012-08-15 41 views
0

如何獲取當前日期 - 3個月?我需要它來進行數據庫查詢以獲取最近3個月內的所有文件。獲取當前日期的NSDate - 3個月

我知道操作「dateByAddingTimeInterval」,但我將不得不減去3個月。

回答

1

取決於你如何定義3個月。如果3個月前的意思是在同一天,你可以做某事像這樣:

NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit |NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]]; 

    NSInteger now_hour = [components hour]; 
    NSInteger now_minute = [components minute]; 
    NSInteger yearx = [components year]; 
    NSInteger monthx = [components month]; 
    NSInteger dayx = [components day]; 

    //1 = january 
    NSInteger monthsMinus3 = (monthx > 3) ? monthx -3 : (monthx +12 -3); 
    NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    [comps setMinute:now_minute]; 
    [comps setHour:now_hour]; 
    [comps setYear:yearx]; 
    [comps setMonth:monthx]; 
    [comps setDay:dayx]; 
    NSDate *threeMonthAgo = [calendar dateFromComponents:comps]; 
當然

你也可以更改月份,而無需創建額外的日期,但我認爲THI是更清晰,更靈活,你喜歡調試的情況以及可能的更改日期,以防你在3個月前定義-n天,這取決於我們是哪個月。例如 - (30 + 31 + 30)或 - (31 + 30 + 31),或者必須考慮二十八天的二十四小時。

再說一次,一切都取決於你3個月前如何定義......但這應該引導你找到解決方案

相關問題