月份的设置无关紧要,单独操作。获取日期的组成部分,更改日期,然后重新组合日期。您可以在更改月份之前或之后执行此操作。
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];