0

次のコードを使用して、現在の日付と時刻から30日後までを検索しています。正常に動作します。しかし、私は今、終了日を30日ではなく60日にしたいと思っています。以下のコードを変更して最大60日を取得するにはどうすればよいですか?終了日を[currentDateComponentsmonth]+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

あなたのコードは、あなたがテキストで説明していることを常に実行するとは限りません。2つの日付が作成されます。1つは当月の初め、もう1つは月末です(月が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 に答える