2013-03-25 30 views
10

我需要從當前日期獲取之前的周和月。NSDate獲取前一個星期,上個月問題

所以我找到的解決方案,可以重新計算當前的日期添加間隔

- dateByAddingTimeInterval 

這params用於在它:

[[NSDate date] dateByAddingTimeInterval: -604800.0](對於前一週獲得)

[[NSDate date] dateByAddingTimeInterval: -2629743.83](爲上月獲得)

正如我認爲獲得星期這個方法運行良好沒有任何問題,因爲每週有七天,間隔不變。但是對於一個月我們有一個問題,因爲每個月都有不同的天數。

+0

這是要在切換到夏令時的地區可以平均周幾周,因爲切換日的一週會縮短/延長一個小時。 – dasblinkenlight 2013-03-25 09:38:57

回答

35

使用NSDateComponents它很容易和準確

NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *comps = [NSDateComponents new]; 
comps.month = -1; 
comps.day = -1; 
NSDate *date = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; 
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date]; // Get necessary date components 
NSLog(@"Previous month: %d",[components month]); 
NSLog(@"Previous day : %d",[components day]); 
+3

這是否會自動處理年份更改? – Siriss 2015-02-03 17:31:31

+0

它的工作..保持它(Y) – 2016-01-28 10:08:31

9

不要使用903484和-23484改變日期

做到這一點的方法:

NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components=[[NSDateComponents alloc] init]; 

components.month=1;//next month 
components.month=-1;//previous month 
//similarly +1 and -1 will give you week and month day etc 
components.week=1; 
components.day=1; 

NSDate *myMonth=[gregorian dateByAddingComponents:components toDate:today options:0]; 
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date]; 
NSInteger yourRequiredValue=[components day]; //day, month, week etc 
相關問題