Adding days to NSDate

后端 未结 9 1799
广开言路
广开言路 2021-01-02 04:34

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         


        
9条回答
  •  南方客
    南方客 (楼主)
    2021-01-02 05:17

    // 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
    

提交回复
热议问题