NSDateを使用して次の日付を取得するにはどうすればいいですか? [重複] 質問する

NSDateを使用して次の日付を取得するにはどうすればいいですか? [重複] 質問する

重複の可能性あり:
iOSと明日を見つける

NSDate を使用して次の日付を取得するにはどうすればよいでしょうか。解決策を送ってください。

ベストアンサー1

以下では、yourDate は入力した NSDate を表し、nextDate は次の日を表します。

// start by retrieving day, weekday, month and year components for yourDate
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:yourDate];
    NSInteger theDay = [todayComponents day];
    NSInteger theMonth = [todayComponents month];
    NSInteger theYear = [todayComponents year];

    // now build a NSDate object for yourDate using these components
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:theDay]; 
    [components setMonth:theMonth]; 
    [components setYear:theYear];
    NSDate *thisDate = [gregorian dateFromComponents:components];
    [components release];

    // now build a NSDate object for the next day
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:1];
    NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:thisDate options:0];
    [offsetComponents release];
    [gregorian release];

おすすめ記事