我使用以下代码从当前日期+时间到30天未来。它工作正常。但是,我现在希望结束日期应该是60天,而不是30天。如何将以下代码更改为最多60天?我尝试将结束日期更改为[currentDateComponents month] +1,但它不起作用。有什么帮助吗?
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *currentDateComponents = [gregorian components:( NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSWeekCalendarUnit) fromDate:date];
NSLog(@"- current components year = %d , month = %d , week = % d, weekday = %d", [currentDateComponents year], [currentDateComponents month], [currentDateComponents week], [currentDateComponents weekday]);
NSArray* calendars = [[CalCalendarStore defaultCalendarStore] calendars];
NSLog(@"calendars.count: %ld", [calendars count]);
debug(@"LogMsg:%@ Date:%@", @"Start looking for new events for pushing iCal to OfferSlot", [NSDate date]);
// 30 days any new or modified calendar (iCal) events will be pushed here to OfferSlot
NSInteger year = [[NSCalendarDate date]yearOfCommonEra];
NSDate *startdate = [NSCalendarDate dateWithYear:year month:[currentDateComponents month] day:1 hour:0 minute:0 second:0 timeZone:nil];
NSDate *enddate = [NSCalendarDate dateWithYear:year month:[currentDateComponents month] day:31 hour:23 minute:59 second:59 timeZone:nil];
答案 0 :(得分:3)
您的代码并不总是按照您在文本中描述的那样执行。它会创建两个日期,一个在当月的开头,一个在月末(如果月份有31天,如果它少于31天,则endDate将在下个月)。如果您在每个月的第1天运行代码,它将创建一个未来30天的NSDate,但仅限于每个月的第1天。
如果你真的想要获得60天后的NSDate,请使用以下代码:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *sixtyDaysOffset = [[NSDateComponents alloc] init];
sixtyDaysOffset.day = 60;
NSDate *sixtyDaysFromNow = [calendar dateByAddingComponents:sixtyDaysOffset toDate:[NSDate date] options:0];