該月份的設置是無關緊要的和單獨的操作。獲取日期的組件,更改日期,然後重新組織日期。您可以在更改月份之前或之後執行此操作。
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];
三江源先生謝謝! – Baconbeastnz 2013-02-25 23:43:27