以下代码会从日期中添加或减去一个月。在那次操作之后,我想明确地将当月的日期设置为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];
答案 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];