2012-04-27 74 views
0

我使用以下代码查找当前日期+时间到未来30天。它工作正常。但是,我想现在的结束日期应该是60天,而不是30天。我如何更改下面的代码来获得60天?我尝试将结束日期更改为[currentDateComponents month] +1,但它不起作用。请帮忙吗?iPhone:将当前日期查找为将来的60天

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

回答

3

您的代码并不总是做你在文中描述的内容。它创建两个日期,一个在本月初,一个在本月底(如果月份有31天,如果它少于31天,您的endDate将在下个月)。如果您在每个月的第一天运行代码,它将创建一个30天后的NSDate,但仅在每个月的第一天。


,如果你真的想要得到的NSDate这是60天从现在开始使用此代码:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *sixtyDaysOffset = [[NSDateComponents alloc] init]; 
sixtyDaysOffset.day = 60; 
NSDate *sixtyDaysFromNow = [calendar dateByAddingComponents:sixtyDaysOffset toDate:[NSDate date] options:0]; 
+0

谢谢你,工作就像一个魅力! – Getsy 2012-04-27 12:31:04

相关问题