0

Is there a good way to check if a NSDate is between now and x days away from now?

I mean without filtering the month-day and doing stuff on it manually.

I use swift to develop and am very new in iOS developing.

Jawwad
  • 1,326
  • 2
  • 9
  • 18
Kingalione
  • 4,237
  • 6
  • 49
  • 84
  • 3
    You would use the same APIs you would use in Objective-C. There are thousands of examples on this. Date comparison is one of the most asked questions on here. – AdamPro13 Feb 18 '15 at 22:58
  • Generally you're going to use NSCalendar and NSDateComponents. – Hot Licks Feb 18 '15 at 22:59
  • I know how to compare the date I just don't know how to increase the current date by x days without filtering the month-day and doing string operations on it – Kingalione Feb 18 '15 at 23:05
  • See `dateByAddingComponents` or `dateByAddingUnit` of `NSCalendar`. – Rob Feb 18 '15 at 23:07
  • Generally you're going to use NSCalendar and NSDateComponents. – Hot Licks Feb 19 '15 at 01:15

1 Answers1

3

If you know how to compare two dates you can use dateByAddingUnit to find out the date xDays from today as follow:

edit/update: Swift 3.x - Swift 4

extension Date {
    func adding(days: Int) -> Date {
        return Calendar.current.date(byAdding: .day, value: days, to: self)!
    }
}

let fiveDaysFromToday = Date().adding(days: 5)  // "Jun 19, 2017 at 5:25 PM"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571