0

我正在使用以下代码查找从当前日期+时间到未来 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];
4

1 回答 1

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];
于 2012-04-27T11:31:02.290 回答