Subtract 7 days from current date

前端 未结 11 921
灰色年华
灰色年华 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

    Swift 3:

    A modification to Dov's answer.

    extension Date {
    
        func dateBeforeOrAfterFromToday(numberOfDays :Int?) -> Date {
    
            let resultDate = Calendar.current.date(byAdding: .day, value: numberOfDays!, to: Date())!
            return resultDate
        }
    }
    

    Usage:

    let dateBefore =  Date().dateBeforeOrAfterFromToday(numberOfDays : -7)
    let dateAfter = Date().dateBeforeOrAfterFromToday(numberOfDays : 7)
    print ("dateBefore : \(dateBefore), dateAfter :\(dateAfter)")
    

提交回复
热议问题