Subtract 7 days from current date

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

    If you're running at least iOS 8 or OS X 10.9, there's an even cleaner way:

    NSDate *sevenDaysAgo = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay
                                                                    value:-7
                                                                   toDate:[NSDate date]
                                                                  options:0];
    

    Or, with Swift 2:

    let sevenDaysAgo = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -7,
        toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
    

    And with Swift 3 and up it gets even more compact:

    let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())
    

提交回复
热议问题