Adding days to NSDate

16,260

Solution 1

// 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] 
                              dateByAddingComponents:dateComponents 
                                              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;

Output:

Original date: 2011-11-17
New date: 2011-12-17

Solution 2

    NSDate *now = [NSDate date];
    int daysToAdd = 1;
    NSDate *newDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

Solution 3

You can add days to an NSDate by adding a time interval

NSDate* newDate = [date dateWithTimeInterval:3600*24*numberOfDays sinceDate:otherDate];

Although if you want to be really accurate about it, and take into account leap seconds, day light saving times and all this kind of thing you might want to use NSDateComponents as described in the Date and Time Programming Guide and Omtara's link.

Solution 4

With iOS 8 and 10.9, you can now actually do this a lot easier. You can add any number of any calendar unit to a date. I declared a really small category method on NSDate to make this even faster (since I just needed adding days throughout my app). Code below.

-(NSDate *)addDaysToDate:(NSNumber *)numOfDaysToAdd {
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay value:numOfDaysToAdd.integerValue toDate:self options:nil];
    return newDate;
}

Key things: NSCalendarUnitDay is what I used to let it know I want to add days. You can change this to the other enum values like months or years.

Since it's a category on NSDate, I'm adding the value to self. If you don't want to declare a category, you'd just take a date in the method parameters, like:

-(NSDate *)addDays:(NSNumber *)numOfDaysToAdd toDate:(NSDate *)originalDate {
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay value:numOfDaysToAdd.integerValue toDate:originalDate options:nil];

    return newDate;
}

I use a NSNumber, but you can easily just use an NSInteger.

Finally, in Swift:

func addDaysToDate(daysToAdd: Int, originalDate: NSDate) -> NSDate? {
        let newDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.DayCalendarUnit, value: daysToAdd, toDate: originalDate, options: nil)
        return newDate
    }

If you want to get rid of the NSDate? and feel comfortable with unwrapping a possible nil (the date adding might fail), you can just return newDate! and get rid of the ? mark.

Solution 5

I suggest you review this article for a cleaner solution.

Share:
16,260
karthick
Author by

karthick

Updated on June 17, 2022

Comments

  • karthick
    karthick almost 2 years

    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];
    
  • jbat100
    jbat100 over 12 years
    That does not answer the question.
  • Kev
    Kev over 12 years
    Whilst this may theoretically answer the question, we would like you to include the essential parts of the linked article in your answer, and provide the link for reference. Failing to do that leaves the answer at risk from link rot.
  • Omtara
    Omtara over 12 years
    The referred content in the linked page is very concise. I once had the same requirement in an iPhone app and found this page useful.
  • Bishal Ghimire
    Bishal Ghimire about 11 years
    @moonlight : what about dateByRemovingComponents ?? what should i do if i need to get new date 1 month previous to present date ?
  • Serhii Mamontov
    Serhii Mamontov about 11 years
    @BishalGhimire setMonth to -1 (for dateComponents) or any number which you want to subtract.
  • Erik van der Neut
    Erik van der Neut about 8 years
    Thanks for that reference Omtara. It's perfect.