Subtract 7 days from current date

前端 未结 11 915
灰色年华
灰色年华 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())
    
    0 讨论(0)
  • 2021-01-29 23:29

    Swift 3

    Calendar.current.date(byAdding: .day, value: -7, to: Date())
    
    0 讨论(0)
  • 2021-01-29 23:31

    FOR SWIFT 3.0

    here is fucntion , you can reduce days , month ,day by any count like for example here , i have reduced the current system date's year by 100 year , you can do it for day , month also just set the counter and store it in an array , you can this array anywhere then func currentTime()

     {
    
        let date = Date()
        let calendar = Calendar.current
        var year = calendar.component(.year, from: date)
        let month = calendar.component(.month, from: date)
        let  day = calendar.component(.day, from: date)
        let pastyear = year - 100
        var someInts = [Int]()
        printLog(msg: "\(day):\(month):\(year)" )
    
        for _ in pastyear...year        {
            year -= 1
                         print("\(year) ")
            someInts.append(year)
        }
              print(someInts)
            }
    
    0 讨论(0)
  • 2021-01-29 23:33

    Swift operator extension:

    extension Date {
        
        static func -(lhs: Date, rhs: Int) -> Date {
            return Calendar.current.date(byAdding: .day, value: -rhs, to: lhs)!
        }
    }
    

    Usage

    let today = Date()
    let yesterday = today - 7
    
    0 讨论(0)
  • 2021-01-29 23:33

    Swift 4.2 iOS 11.x Babec's solution, pure Swift

    extension Date {
      static func changeDaysBy(days : Int) -> Date {
        let currentDate = Date()
        var dateComponents = DateComponents()
        dateComponents.day = days
        return Calendar.current.date(byAdding: dateComponents, to: currentDate)!
      }
    }
    
    0 讨论(0)
提交回复
热议问题