Adding days to NSDate

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

    in Swift 2.1.X and xcode 7.1 OSX 10.10.5 ,you can add any number of days forward and backwards using function

    func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
    {
        let dateComponents = NSDateComponents()
        let CurrentCalendar = NSCalendar.currentCalendar()
        let CalendarOption = NSCalendarOptions()
    
        dateComponents.day = NumberOfDaysToAdd
    
        let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
        return newDate!
    }
    

    function call for incrementing current date by 9 days

    var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
    print(newDate)
    

    function call for decrement current date by 80 days

    newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
    print(newDate)
    

提交回复
热议问题