Subtract 7 days from current date

前端 未结 11 1080
灰色年华
灰色年华 2021-01-29 22:41

It seems that I can\'t subtract 7 days from the current date. This is how i am doing it:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:N         


        
11条回答
  •  情深已故
    2021-01-29 23:27

    dymv's answer work great. This you can use in swift

    extension NSDate {    
        static func changeDaysBy(days : Int) -> NSDate {
            let currentDate = NSDate()
            let dateComponents = NSDateComponents()
            dateComponents.day = days
            return NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
        }
    }
    

    You can call this with

    NSDate.changeDaysBy(-7) // Date week earlier
    NSDate.changeDaysBy(14) // Date in next two weeks
    

    Hope it helps and thx to dymv

提交回复
热议问题