2013-02-25 94 views
1

下面的代碼從日期中增加或減去一個月。在那個操作之後,我想明確地將每月的一天設置爲15.我該如何實現?在NSDate上更改月份的日期

NSDateComponents* offsetComponents = [[NSDateComponents alloc]init]; 
int magnitude = isLeft ? 1 : -1; 
[offsetComponents setMonth:magnitude]; 
NSCalendar* calendar1 = [NSCalendar currentCalendar]; 
updatedDate = [calendar1 dateByAddingComponents:offsetComponents toDate:dateRef options:0]; 

回答

6

該月份的設置是無關緊要的和單獨的操作。獲取日期的組件,更改日期,然後重新組織日期。您可以在更改月份之前或之後執行此操作。

NSDate * today = [NSDate date]; 
NSCalendar * cal = [NSCalendar currentCalendar]; 

NSDateComponents * offsetComponents = [NSDateComponents new]; 
[offsetComponents setMonth:-1]; 

// Either 

NSDate * sameDayLastMonth = [cal dateByAddingComponents:offsetComponents 
               toDate:today 
               options:0]; 

NSDateComponents * lastMonthComps = [cal components:NSUIntegerMax 
              fromDate:sameDayLastMonth]; 
[lastMonthComps setDay:15]; 

NSDate * fifteenthOfLastMonth = [cal dateFromComponents:lastMonthComps]; 

// or 

NSDateComponents * todayComps = [cal components:NSUIntegerMax 
             fromDate:today]; 
[todayComps setDay:15]; 

NSDate * fifteenth = [cal dateFromComponents:todayComps]; 

NSDate * fifteenthOfLastMonth = [cal dateByAddingComponents:offsetComponents 
                toDate:fifteenth 
                options:0]; 

或者,更容易(廢話,我應該首先做到了這一點):

NSDate * today = [NSDate date]; 
NSCalendar * cal = [NSCalendar currentCalendar]; 

NSInteger offset = arc4random_uniform(2) ? -1 : 1; 

NSDateComponents * comps = [cal components:NSUIntegerMax 
            fromDate:today]; 
[comps setDay:15]; 
[comps setMonth:[comps month] + offset]; 

NSDate * newDate = [cal dateFromComponents:comps]; 
+0

三江源先生謝謝! – Baconbeastnz 2013-02-25 23:43:27

相關問題