سؤال

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@",dateString);


// Retrieve NSDate instance from stringified date presentation
NSDate *dateFromString = [dateFormatter dateFromString:dateString];

// Create and initialize date component instance
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:2];

// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar]
                   dateByAddingComponents:dateComponents
                   toDate:dateFromString options:0];

NSLog(@"Original date: %@", [dateFormatter stringFromDate:dateFromString]);
NSLog(@"New date: %@", [dateFormatter stringFromDate:newDate]);

OutPut

   2013-05-17
   Original date: 2013-05-17
    New date: 1412647-09-06

I add 2 day to that. The new date should be "2013-05-19?. Can anyone tell me what I wrong? Thank in advance.

هل كانت مفيدة؟

المحلول

I assume that you forgot to initialize the day variable. If you add

NSUInteger day = 2;

then your code produces the expected result in my test program.

نصائح أخرى

The init methode of NSDateComponents does not initializes the components. Thus, e.g., year is undefined. Form Apple's documentation:

An instance of NSDateComponents is not responsible for answering questions about a date beyond the 
information with which it was initialized. For example, if you initialize one with May 6, 2004,   
its weekday is NSUndefinedDateComponent
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top