1

下面的代码从日期中添加或减去一个月。在该操作之后,我想明确地将月份中的日期设置为 15。我该如何实现呢?

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];
4

1 回答 1

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];
于 2013-02-25T22:37:04.790 回答