Adding days to NSDate

后端 未结 9 1754
广开言路
广开言路 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:09

    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.

提交回复
热议问题