Subtract 7 days from current date

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

    Swift 4.2 - Mutate (Update) Self

    Here is another way the original poster can get one week ago if he already has a date variable (updates/mutates itself).

    extension Date {
        mutating func changeDays(by days: Int) {
            self = Calendar.current.date(byAdding: .day, value: days, to: self)!
        }
    }
    

    Usage

    var myDate = Date()       // Jan 08, 2019
    myDate.changeDays(by: 7)  // Jan 15, 2019
    myDate.changeDays(by: 7)  // Jan 22, 2019
    myDate.changeDays(by: -1) // Jan 21, 2019
    

    or

    // Iterate through one week
    for i in 1...7 {
        myDate.changeDays(by: i)
        // Do something
    }
    

提交回复
热议问题