2012-04-27 35 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