karthick karthick - 1 year ago 150
Objective-C Question

Adding days to NSDate

I want add days to a date, I got many codes for this but none of them are working for me below shown is my code,please somebody help me to fix this issue

int daysToAdd=[[appDlegateObj.selectedSkuData
objectForKey:@"Release Time"] intValue];

NSTimeInterval secondsForFollowOn=daysToAdd*24*60*60;

NSString *dateStr=[contentDic objectForKey:@"Date"];

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];

[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSDate *dateFromString=[[NSDate alloc]init];

dateFromString=[dateFormatter dateFromString:dateStr];

[dateFormatter release];

NSDate *date=[dateFromString dateByAddingTimeInterval:secondsForFollowOn];

Answer Source
// Initialize stringified date presentation
NSString *myStringDate = @"2011-11-17";

// How much day to add
int addDaysCount = 30;

// Creating and configuring date formatter instance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

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

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

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

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

// Clean up
[dateComponents release], dateComponents = nil;
[dateFormatter release], dateFormatter = nil;


Original date: 2011-11-17
New date: 2011-12-17
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download