23

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

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

4

5 に答える 5

57

以下では、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];
于 2009-07-04T07:07:20.453 に答える
31

このメソッドはどうですか?

http://www.drobnik.com/touch/2009/05/adding-days-to-nsdate/

NSDate *now = [NSDate date];
int daysToAdd = 50;  // or 60 :-)

// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(@"Clean: %@", newDate2);
于 2010-06-03T11:15:23.237 に答える
3

この方法は私にとってはうまくいくと思います。

NSString *zajtra = [[NSDate date] dateByAddingTimeInterval:86400];
于 2010-08-24T10:19:40.963 に答える
2

//以下のコードをinitメソッドまたはviewDidloadに追加します

[[NSUserDefaults standardUserDefaults] setObject:[NSDate date]  forKey:@"Date"];

//次または前の日付を取得する場所にこのコードを追加します

NSDate *tomorrow = [[NSUserDefaults standardUserDefaults] valueForKey:@"Date"];
NSTimeInterval secondsPerDay = 24 * 60 * 60;    
NSDate *date = [tomorrow addTimeInterval:secondsPerDay]; //Change NSDate *date = [tomorrow addTimeInterval:-secondsPerDay]; for yesterday
tomorrow = date;
[self setDate:tomorrow];
dateTextField.text = [self getDate];        
[[NSUserDefaults standardUserDefaults] setObject:tomorrow  forKey:@"Date"]; 
于 2009-07-06T04:51:27.857 に答える